HTML5 CANVAS
Rectangles Arcs Lines Features we won’t look at Images Drag and drop Animation Widely supported DRAWING PICTURES IN HTML (AND JAVASCRIPT)
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 HOW TO DO IT
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 SET UP
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; RECTANGLES
Need to create a gradient object var gradient = context.createLinearGradient(x 0, y 0, x 1, y 1 ); 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; GRADIENTS
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(); ARCS
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(); LINES
Mark Pilgrim, Dive into HTML5 Chapter 4: Let’s Call it a Draw(ing Surface) Chapter 4: Let’s Call it a Draw(ing Surface) HTML5 Canvas Basic Tutorials HTML5 Canvas Basic Tutorials RESOURCES