1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | window.requestAnimFrame = (function(callback){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); }; })(); function animate(plane, lastTime){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); // update var date = new Date(); var time = date.getTime(); var timeDiff = lastTime - time; plane.theta += timeDiff * plane.rotationSpeed / 1000; plane.tilt = Math.sin(plane.theta / 2); // clear context.clearRect(0, 0, canvas.width, canvas.height); // draw context.save(); context.translate(canvas.width / 2, canvas.height / 2); context.scale(1, plane.tilt); context.rotate(plane.theta); var planeColor = plane.tilt >= 0 ? "red" : "blue"; context.fillStyle = planeColor; context.fillRect(-plane.width / 2, -plane.height / 2, plane.width, plane.height); context.restore(); // request new frame requestAnimFrame(function(){ animate(plane, time); }); } window.onload = function(){ var plane = { width: 200, height: 100, theta: 0, tilt: 1, rotationSpeed: 2 }; var date = new Date(); var time = date.getTime(); animate(plane, time); }; |
Modified on November 24th, 2011
by Eric Rowell