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