Scripting canvas: Zoom!

Unlike SVG, which generates objects even if scripting is disabled, the canvas element is dependent on JavaScript. JavaScript is used to create the canvas element, the contained objects, annotate the objects, position them, and add the pretties. I covered all of this in Chapter 12. What I didn't cover in the last chapter is that, just like SVG, canvas is also interactive and dynamic.

I must seem as if I prefer SVG over canvas, and I do. The SVG specification is much broader in scope and capability, not to mention it works without scripting. Still, there are characteristics of the canvas element I really like, such as being able to dynamically generate the tick marks on a clock via an algorithm rather than have to place them manually. What I especially like about the canvas element, though, is the ability to zoom into a picture.

Capturing Events on the canvas Element

The biggest difference when working with the canvas element and other web page elements is that it's one single piece, no matter what's added to the canvas. As such, when you're capturing events, you're capturing them for the canvas element, not the individual canvas items. As you can imagine, capturing the position of an event is pretty important.

Example 12-14 is web page with a canvas element consisting of an external photo pulled into the canvas. Clicking on the image adds a small rectangle to the canvas. It's important to be aware of one challenge associated with the application: the mouse event ...

Get Painting the Web now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.