HTML and CSS Reference
In-Depth Information
the previous example is one of the world's least exciting
animations implemented with the <canvas> element. Pac - man it
isn't, but this simple demo is enough to demonstrate
the general principles, here's the code used to generate it:
ThE init() function will
be called on page load.
function init() {
set an interval to call the
draw() function every 1000
draw the
initial state
to start.
function draw(){
var now = new Date();
= now.toLocaleString();
var canvas = document.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(255,0,0)';
ctx.fillRect(now.getSeconds() * 4,50,100,100);
ctx.strokeStyle = 'rgb(0,127,127)';
ctx.moveTo(now.getSeconds() * 4,50);
ctx.lineTo(now.getSeconds() * 4 + 100,150);
ctx.lineWidth = 5;
As a shortcut, the
state of the
animation is given
by the current time.
explicitly clear the
canvas. the previous
step of the drawing
won't be removed
you need to reset the path so the
previous path isn't redrawn every
Here's what happens if you forget to explicitly start a new path.
If you forget to close any paths you have open, they'll be redrawn as
you iterate through your animation steps along with any additions to
the path. Clearing the pixels on the context doesn't reset the path.
The <canvas> element allows precise, pixel-level control over what is dis-
played and is already considered a rival to Flash in the browser game
marketplace because it works on iPhones and iPads. Experimental
Search WWH ::

Custom Search