Game Development Reference
In-Depth Information
are several ways to draw a regular JPG, GIF, or PNG image right on the canvas, in-
cluding functions that handle scaling images from source to destination.
One other note that we need to make about the canvas element is that it follows the
same origin policy. That means, in order for us to be able to draw an image onto
a canvas context, the script attempting to draw the image must be served from the
same domain (along with the same protocol and port number) as the image. Any
attempt to load an image from a different domain into the canvas context and the
browser will throw an exception.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0, this.width,
this.height);
};
img.src = "img/html5-logo.png";
The simplest call to draw an image only takes five parameters. The first is a referen-
ce to an image. The next two parameters are the x and y position where that image
will be drawn onto the canvas, and the last two parameters are the width and height
to paint the image onto the canvas. If the last two parameters don't maintain the as-
pect ratio of the original image, the result will be distortion, rather than clipping. Also,
note that, if the original image is larger than the canvas, or if the image is drawn from
an offset such that part of the image runs off the canvas, that extra data will simply
not be drawn (obviously), and the canvas will just ignore those pixels outside the
viewable area:
Search WWH ::




Custom Search