http://www.codeproject.com/KB/HTML/HTML5Animations.aspx
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Animations in HTML5 using the canvas element</title>
<script></script>
</head>
<body>
<canvas id="canvas" width="1000" height="600">Your browser does not support the
<code><canvas></code>-element. Please think about updating your browser!</canvas>
<div id="controls">
<button type="button" onclick="speed(-0.1);">Slower</button>
<button type="button" onclick="play(this);">Play</button>
<button type="button" onclick="speed(+0.1);">Faster</button>
</div>
</body>
</html>
JS代码
function drawCanvas() {
c.clearRect(0, 0, c.canvas.width, c.canvas.height); // Clear the (displayed)
// canvas to avoid errors
c.save(); // Saves the current state of properties (coordinates!)
drawGrass(); // Draws the background (grass)
c.translate(carX, 0); // Does some coordinate transformation
drawCar(); // Draws the car (redraws hidden canvas)
c.drawImage(w.canvas, 0, carY); // Draws the car actually to visible canvas
c.restore(); // Restores to last saved state (original coordinates!)
carX += dx; // Increases the position by the dx we set per time
carAlpha += dx / radius; // Increases the angle of the tires by the ratio
if(carX > c.canvas.width) // We keep some periodic boundary conditions
carX = -carWidth - 10; // We could also reverse the speed dx *= -1;
}