240 likes | 714 Views
HTML5 Canvas. 24 April 2014. Drawing pictures in HTML (and Javascript ). Rectangles Arcs Lines Features we won’t look at Images Drag and drop Animation Widely supported. How to do it. Canvas tag in HTML Id required Resizing must be done in tag, NOT CSS
E N D
HTML5 Canvas 24 April 2014
Drawing pictures in HTML(and Javascript) • Rectangles • Arcs • Lines • Features we won’t look at • Images • Drag and drop • Animation • Widely supported
How to do it • Canvas tag in HTML • Id required • Resizing must be done in tag, NOT CSS • If you go outside canvas, no error, just doesn’t show • JavaScript to DRAW: step by step
Set up • Need to identify the canvas • Create a javaScript object that represents the canvas (context) • Methods associated with object var canvas = document.getElementById("rectangles"); var context = canvas.getContext("2d"); • Code needs to wait until loading completes document.addEventListener('DOMContentLoaded',domloaded,false); function domloaded() { } • Drawn in order of execution
rectangles • Most straightforward • Define by location of upper left corner and size • Grid is defined with (0,0) as upper left corner context.fillRect(x, y, width, height); • Set color and then define the rectangle context.fillStyle= "#EF5B84"; context.fillRect(100, 100, 100, 200); • Color • Always a string • Same formats as in CSS • Opacity: applies to what follows context.globalAlpha= 0.5;
gradients • Need to create a gradient object var gradient = context.createLinearGradient(x0, y0, x1, y1); • If x’s or y’s are 0, no change in that direction • If non-zero, must match the rectangle locations • Stops gradient.addColorStop(0, “blue"); gradient.addColorStop(1, “#FFFFFF"); • Can have as many transitions as you want • Define at relative points from 0 to 1 • Define color at that point • Use gradient rather than color in fillStyle context.fillStyle= gradient;
arcs • Circles and arcs context.arc(x, y, radius, start-angle, end-angle, dir); • Outline (“pencil”) and then draw (“ink”) • Pencil context.beginPath(); context.arc(x, y, radius, 0, Math.PI * 2, false); context.closePath(); /* closes the shape */ • Fill context.fillStyle = "#000"; context.fill(); • Ink context.strokeStyle= "#000"; context.stroke();
lines • Pencil up, pencil down • Start (same as arcs) context.beginPath(); • Position context.moveTo(x,y); • Draw (pencil) context.lineTo(x,y); • If you want to close the shape (same as arcs) context.closePath(); • Ink (same as arc) context.strokeStyle = "#000"; context.stroke();
resources • Mark Pilgrim, Dive into HTML5 • Chapter 4: Let’s Call it a Draw(ing Surface) • HTML5 Canvas Basic Tutorials