HTML and CSS Reference
In-Depth Information
TIP The context object
has an attribute called
canvas , which has a back-refer-
ence to the canvas element it's
part of. You can use this to go
back to the canvas and read the
height and width—useful for
when you only have the context.
that draws the path for a spiral and uses stroke to draw it on
the canvas):
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
drawSpiral(); // the complicated magic mathematics
setInterval(function () {
ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2,
ctx.canvas.width, ctx.canvas.height);
ctx.rotate(Math.PI / 180 * 0.5) // 1/2 a degree
}, 10);
The only caveat I have to deal with is clearing the canvas. I
would normally use clearRect(0, 0, width, height) , but since
translate has moved the 0, 0 position to the centre of the can-
vas, I need to manually specify the top left, as you see in the
previous code listing.
Capturing images
As well as drawing lines and shapes, you can also copy images
from other sources, specifi cally images, videos, and other can-
vas elements. I've already shown that you can use images as
the source of a createPattern fi ll. ll. . Y of u c a n a ll. s of d r a w fi m a g e s
straight onto your canvas. You can even crop images and
manipulate the images as they are copied on.
Since you can capture an image from a video element, this
makes for some interesting opportunities. There's already lots
of demos out in the wild, including dynamically injecting content
into video, green screen replacement for video, and facial rec-
ognition—all using combinations of canvas and video all written
in JavaScript.
The capturing and drawing is done entirely through the drawImage
method, which accepts the different HTML element sources men-
tioned before, and accepts the following three sets of arguments:
drawImage(image, dx, dy)
drawImage(image, dx, dy, dw, dh)
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
where d is the destination position and s is the source. For
example, if I took Bruce's synergies video from Chapter 4, and
Search WWH ::

Custom Search