在html5 canvas中繪制圖像動畫效果,你需要繪制出每一幀的圖像,然后在一個極短的時間內從一幀過渡到下一幀,形成動畫效果。 示例要在html5畫布上繪制動畫,您需要在畫布上繪制和重新繪制動畫的幀。您需要非常快地這樣做,以使許多圖像看起來像動畫。 function animate() {
reqAnimFrame = (window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
var self = this, start, finish;
return window.setTimeout(function() {
start = +new Date();
callback(start);
finish = +new Date();
self.timeout = 1000/60 - (finish - start);
}, self.timeout);
});
reqAnimFrame(animate);
draw();
}animate()函數首先獲得對該requestAnimationFrame() 函數的引用。請注意,此函數在不同的瀏覽器中可能具有不同的名稱。將該變量 reqAnimFrame設置為所有這些不為null的可能函數。 <canvas id="ex1" width="500" height="170" style="border: 1px solid #cccccc;">
HTML5 Canvas not supported
</canvas>
<script>var x = 0;
var y = 15;
var speed = 5;
function animate() {
reqAnimFrame = (window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
var self = this, self.timeout);
});
reqAnimFrame(animate);
x += speed;
if(x <= 0 || x >= 475){
speed = -speed;
}
draw();
}
function draw() {
var canvas = document.getElementById("ex1");
var context = canvas.getContext("2d");
context.clearRect(0, 0, 500, 170);
context.fillStyle = "#ff00ff";
context.fillRect(x, y, 25, 25);
}
animate();
</script> |