直接看代码哈
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);
};