<script> // DECLARE VARIABLES var canvas, context; var date, time; var inc; // DECLARE requestAnimFrame window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); } })(); // INITIALIZE ALL FUNCTIONS function init() { canvas = document.getElementById("myCanvas"); context = canvas.getContext("2d"); counter = 0; inc = 10; var myRectangle = { x: 0, y: 50, width: 50, height: 50, borderWidth: 5 } date = new Date(); time = date.getTime(); animate(time, myRectangle); } function clearBkgd() { context.clearRect(0, 0, canvas.width, canvas.height); } function animate(lastTime, myRectangle) { clearBkgd(); // update date = new Date(); time = date.getTime(); var timeDiff = time - lastTime; var linearSpeed = 20; // pixels / second var linearDistEachFrame = linearSpeed * timeDiff / 1000; if (myRectangle.x > canvas.width - myRectangle.width - myRectangle.borderWidth || myRectangle.x < 0) { inc *= -1; } else { inc *= 1; } myRectangle.x += linearDistEachFrame * inc; lastTime = time; document.getElementById('display').innerHTML = myRectangle.x + " // " + linearDistEachFrame ; // draw context.beginPath(); context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height); context.fillStyle = "#8ED6FF"; context.fill(); context.lineWidth = myRectangle.borderWidth; context.strokeStyle = "black"; context.stroke(); // request new frame requestAnimFrame(function() { animate(lastTime, myRectangle); }); } </script>