Zielony Smok - logo witryny

Oscylacja w poziomie

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 amplitude = 150;
	var period = 2000;
	var centerX = canvas.width / 2 - rectangle.width / 2;
	var nextX = amplitude * Math.sin(time * 2 * Math.PI / period)
			+ centerX;
	rectangle.x = nextX;
	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);