HTML and CSS Reference
In-Depth Information
Capturing images
As well as drawing lines and shapes, you can copy images from
other sources, specifically images, videos, and other canvas
elements. I've already shown that you can use images as the
source of a createPattern fill. You can also draw images straight
onto your canvas. You can even crop and manipulate the
images as they're copied:
var ctx = document.getElementById('mycanvas').
img = new Image();
img.onload = function () {
ctx.canvas.height = 500;
ctx.canvas.width = 500;
ctx.drawImage(this, 10, 10, 100, 100, 0, 0, 500, 500);
img.src = 'bruce-and-remy-promo-pics.jpg';
The code above is a simple example of how I can dynamically
create an image on the fly, and once it's loaded I can draw a sec-
tion of it in to my canvas. As we'll see in a moment you have a
few ways of using the drawImage method, and here what I've done
is take a 100x100 pixel crop from 10 pixels left and 10 pixels right,
and stretch it in to the canvas over 500 pixels wide and tall.
Since you can also capture an image from a video element, this
makes for some interesting opportunities. There's already lots
of demos out in the wild, showing some interesting effects like
dynamically injecting content into video, green screen replace-
ment for video, and facial recognition—all using combinations of
canvas and video, all written in JavaScript.
The capturing and drawing is done entirely through the drawImage
method, which needs a reference to the source (an image, video,
or canvas element), a target position (the top/left coordinates of
where you want to draw the image in your canvas), and a few
optional arguments that allow you to crop and scale the image:
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 synergy video from Chapter 4, and
TIp All 2D drawing con-
texts have a back refer-
ence to the canvas which they
draw against. This means you
don't have to pass around two
variables to functions, you can
just pass the context and get
the back reference to the can-
vas element if you wanted to
change the height, width, or get
the data url.
Search WWH ::

Custom Search