BIT-101 [2003-2017]

JavaScript Day 19: Images


I figured we need to take at least a couple days or more to talk about images and JavaScript and Canvas. It’s a pretty useful subject.

So far, we’ve been drawing everything with lines and arcs. Maybe a rect here or there. But canvas can also draw bitmap images. There are a few different ways to get bitmap images. The most obvious is through an image tag on the html page. Say we have a setup like this:

[php lang=“HTML”]

[/php]

Just a canvas and a funny picture in divs so they don’t overlap. We can draw that image onto the canvas with the following script:

[php lang=“JavaScript”]$(function () {
$("#image").load(
function () {
var canvas, context, image;

image = $("#image")[0];
canvas = $("#canvas")[0];
context = canvas.getContext(“2d”);
context.drawImage(image, 0, 0);
}
);
});[/php]

Here we use the jQuery document ready function to kick start things as usual, then wait for the image to load. If the image hasn’t loaded yet, obviously you can’t draw it. The document ready function fires when the html document itself loads and initializes, but still may need to load referenced content, such as images. Listening for the load of an image goes like this:

$(imageReference).load(
function() {
// do something
}
);

Here, we get the image reference by id, “#image”. Once it’s loaded, we get a reference to it, as well as the canvas and context, and call context.drawImage(image, x, y). Pretty straightforward.

There’s an overload for the drawImage function which looks like this: drawImage(image, x, y, w, h). This defines a rectangle to draw the image into. If that rectangle is not exactly the same size as the source image, the image will be scaled to fit. We’ll do something a little funky do demonstrate that:

[php lang=“JavaScript”]$(function () {
$("#image").load(
function () {
var canvas, context, image, w, h, phase = 0;

image = $("#image")[0];
w = image.width;
h = image.height;
canvas = $("#canvas")[0];
context = canvas.getContext(“2d”);

setInterval(function () {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 50, 50, w + Math.sin(phase) * 50, h + Math.cos(phase) * 50);
phase += 0.01;
}, 1000/30);
}
);
});[/php]

Here we are getting the original width and height of the image, storing them in vars w and h, then running some simple trig to oscillate them larger and smaller in a setInterval function. You can see the result here:

https://www.bit-101.com/jscanvas/mar19.html

OK, that’s it for today. Tomorrow we’ll see yet another overload for draw image and how we can do another form of animation with that.

« Previous Post
Next Post »