Zielony Smok - logo witryny

Funkcja requestAnimationFrame()

Zawartość możesz zobaczyć w
przeglądarce obsługującej element <canvas>
z kontekstem "2d"

Listing

window.requestAnimFrame = (function(callback) {
	return window.requestAnimationFrame
			|| window.webkitRequestAnimationFrame
			|| window.mozRequestAnimationFrame
			|| window.oRequestAnimationFrame
			|| window.msRequestAnimationFrame
			|| function(callback) {
				window.setTimeout(callback, 1000 / 42);
			};
})();
function drawRectangle(rectangle, context) {
	context.beginPath();
	context.rect(rectangle.x, rectangle.y, rectangle.width,
			rectangle.height);
	context.fillStyle = 'red';
	context.fill();
	context.lineWidth = rectangle.borderWidth;
	context.strokeStyle = 'black';
	context.stroke();
};
function animate(rectangle, canvas, context, startTime) {
	var time = (new Date()).getTime() - startTime;
	var linearSpeed = 100;
	var newX = linearSpeed * time / 1000;
	if (newX < canvas.width - rectangle.width
			- rectangle.borderWidth / 2) {
		rectangle.x = newX;
	}
	context.clearRect(0, 0, canvas.width, canvas.height);
	drawRectangle(rectangle, context);
	requestAnimFrame(function() {
		animate(rectangle, canvas, context, startTime);
	});
};
var cv = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var rectangle = {
	x : 0,
	y : 75,
	width : 100,
	height : 50,
	borderWidth : 2
};
drawRectangle(rectangle, ctx);
setTimeout(function() {
	var startTime = (new Date()).getTime();
	animate(rectangle, cv, ctx, startTime);
}, 500);
    

inne animacje wykorzystujące tę funkcję: