Canvas
The HTML 5 specification has introduced a slew of new and exciting technologies to the web. Here we’ll expand on just one: the Canvas API. It’s for drawing pretty, whizzy things.
The first thing to know is that canvas
is a new element in the HTML 5 specification. To begin drawing on the canvas
, you grab hold of it and retrieve a particular context - either 2d
or webgl
:
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
From there you can begin drawing, filling and stroking shapes and text on the canvas. Here’s an example that draws a simple square on a canvas.
<canvas></canvas> <script>
var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'); ctx.fillRect(10, 10, 10, 10);
</script>
Try this out on a page to see a little black square!
The getContext
function retrieved the correct context, which is an object whose methods are used to draw, fill and generally modify the canvas. Above we’re using fillRect
, which takes the x and y position of the top left corner of the rectangle as the first two arguments, and the width and height dimensions as the latter two.
Animation
canvas
works a bit like a real canvas - pixels are drawn and layered on top of each other until you erase - clear - them. This means that if you want to animate something moving across a canvas you have to repeatedly clear the canvas (or a section of it) and redraw the scene.
In the next example we’ve animating the square bouncing around the canvas
, which automatically resizes to fill the screen. loop is the business part of the code. The clearRect
function is used to clear the entire canvas before each frame.
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
var resize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.addEventListener('resize', resize);
window.addEventListener('load', function () {
resize();
var pos, vel;
pos = {
x: 10,
y: 10
};
vel = {
x: 1,
y: 1
};
var loop = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
pos.x += vel.x;
pos.y += vel.y;
if (pos.x < 5 || pos.x > canvas.width - 5) {
vel.x *= -1;
}
if (pos.y < 5 || pos.y > canvas.height - 5) {
vel.y *= -1;
}
ctx.fillRect(pos.x - 5, pos.y - 5, 10, 10);
};
setInterval(loop, 1000 / 60);
});
There’s lots to explore with canvas, this was just a very shallow look at it. There are many specialized resources on the web so, to find out more, Google is your best friend.