moving html 5 icon
by nhulea
HTML
<html>
<body>
<canvas id="testCanvas" width="400" height="400">Your browser is too old</canvas>
</body>
</html>
JavaScript
//loop helper
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function () {
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, fps) {
window.setTimeout(callback, 1000 / 60); // frames per second
};
})();
}
//position
var x = 0;
//canvas
var canvas = null;
var ctx = null;
//image
var image = new Image();
image.src = "http://aux4.iconpedia.net/uploads/868888537436999746.png";
//loop
var lastTs = Date.now();
function loop() {
var delta = Date.now() - lastTs;
lastTs = Date.now();
//request anim frame
requestAnimationFrame(loop);
//set canvas once able
if (!canvas) {
var temp = document.getElementById("testCanvas");
if (temp) {
canvas = temp;
ctx = canvas.getContext('2d');
}
}
//update and render if able
if (canvas) {
//increase x
x += 300 * delta / 1000;
//start from beginning
if (x > 250) {
x = 250;
}
//clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
//image
ctx.drawImage(image, x, 200);
}
}
//start
loop();