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() {
draw();
window.setInterval(draw,1000);
}
set an interval to call the
draw() function every 1000
milliseconds.
draw the
initial state
to start.
function draw(){
var now = new Date();
document.getElementById('timestamp').innerHTML
= now.toLocaleString();
var canvas = document.getElementById('mycanvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.clearRect(0,0,320,240);
ctx.fillStyle = 'rgb(255,0,0)';
ctx.fillRect(now.getSeconds() * 4,50,100,100);
ctx.beginPath();
ctx.strokeStyle = 'rgb(0,127,127)';
ctx.moveTo(now.getSeconds() * 4,50);
ctx.lineTo(now.getSeconds() * 4 + 100,150);
ctx.lineWidth = 5;
ctx.stroke();
}}
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
automatically.
you need to reset the path so the
previous path isn't redrawn every
iteration.
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