HTML 5 CANVAS SAVING INFORMATION BETWEEN FUNCTION CALLS
HTML 5 CANVAS
SAVING INFORMATION BETWEEN FUNCTION CALLS
SAVING INFORMATION Can I keep information between calls to a function? § Why would I want to do it? Possibilities § Store and retrieve values from the HTML page § Possible but can be cumbersome § Have a java. Script variable OUTSIDE the function § Known as a global variable Snippets for the carousel § elem_ illustrates writing to src outside of a form
CANVAS
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 <canvas id=“c" height="400" width="800"> </canvas> Java. Script to DRAW: step by step
SET UP Need to identify the canvas Create a java. Script object that represents the canvas (context) Methods associated with object var canvas = document. get. Element. By. Id(“c"); var context = canvas. get. Context("2 d"); Code needs to wait until loading completes e); § Onload § Faster alternative document. add. Event. Listener('DOMContent. Loaded', domloaded, fals 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. fill. Rect(x, y, width, height); Set color and then define the rectangle context. fill. Style = "#EF 5 B 84"; context. fill. Rect(100, 200); Color § Always a string § Same formats as in CSS Opacity: applies to what follows context. global. Alpha = 0. 5;
ARCS Circles and arcs context. arc(x, y, radius, start-angle, end-angle, dir); Outline (“pencil”) and then draw (“ink”) Pencil context. begin. Path(); context. arc(x, y, radius, 0, Math. PI * 2, false); context. close. Path(); /* closes the shape */ Fill context. fill. Style = "#000"; context. fill(); Ink context. stroke. Style = "#000"; context. stroke();
LINES Pencil up, pencil down Start (same as arcs) context. begin. Path(); Position context. move. To(x, y); Draw (pencil) context. line. To(x, y); If you want to close the shape (same as arcs) context. close. Path(); Ink (same as arc) context. stroke. Style = "#000"; context. stroke();
RESOURCES Mark Pilgrim, Dive into HTML 5 Chapter 4: Let’s Call it a Draw(ing Surface) HTML 5 Canvas Basic Tutorials
- Slides: 11