Html
Let's write the code in the file 1.html
<html>
<!-- heading -->
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<!-- page -->
<body>
<!-- HTML canvas -->
<canvas id="canvas1" width='400px' height='400px'></canvas>
<!-- JavaScript Functions -->
<script>
// we upload pictures from files
function loadImages(files, callbackAllFilesLoaded)
{
// count the number of files
var countFilesToLoad = 0;
for (var fileId in files)
{
countFilesToLoad++;
}
var images = {};
for (var fileId in files)
{
// create a blank picture
images[fileId] = new Image();
// event onload
images[fileId].onload = function()
{
// when all the files are loaded, call our function callbackAllFilesLoaded to draw a picture
if ( --countFilesToLoad <= 0 )
{
callbackAllFilesLoaded(images);
}
};
// uploading a picture
images[fileId].src = files[fileId];
}
}
function AnimationInit()
{
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback)
{
window.setTimeout(callback, 1000 / 60);
};
})();
}
</script>
<!-- master code -->
<script>
function MyAnimation(context, canvas, loadedImages, data)
{
<!-- clear everything on canvas -->
context.clearRect(0, 0, canvas.width, canvas.height);
// draw a picture by position x,y
context.drawImage(loadedImages.tree, data.xPos, data.yPos);
// change the position of the picture
data.xPos = data.xPos>410 ? 0 : data.xPos + 2.6;
// request new frame
requestAnimFrame(function(){
MyAnimation(context, canvas, loadedImages, data);
});
}
<!-- file -->
var files = {
tree : "./tree.jpg"
};
<!-- context for drawing -->
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
<!-- upload images -->
loadImages(files, function (loadedImages)
{
<!-- initializing an animation -->
AnimationInit();
<!-- data to move -->
var data = {
xPos: 0,
yPos: 20
};
<!-- start endless animation -->
MyAnimation(context, canvas, loadedImages, data);
});
</script>
</body>
</html>
tree.jpg the picture must be in the same folder as the file
1.html