HTML5 > Canvas Animation

Animating sequence of Images in HTML5

How to create animation using sequence of images in HTML5?

In previous post, we learnt how to start, stop and cancel HTML5 animation, in this post, we shall learn how to create animation using sequence of images in HTML5 Canvas.

Animation using sequence of images in HTML5 Canvas


    <canvas id="Canvas1" width="600" height="400" style="border:5px solid green;">
        Canvas is not supported in your browser
    <br />
    <input type="button" onclick="StartAnimation()" value="Start Animation" />
    <input type="button" onclick="StopAnimation()" value="Stop Animation" />
    <input type="button" onclick="ResetCanvas()" value="Reset" />

Same as previous post, we have Start Animation, Stop Animation and Reset button to start, stop and reset the animations.

JavaScript code

        var canvas;
        var context;
        var photo;
        var timer;
        var count = 0;

        function StartAnimation() {

            img = new Image();
            canvas = document.getElementById("Canvas1");
            context = canvas.getContext("2d");
           //  img.src = 'images/image1.JPG';

        function AnimateNow() {
            img.src = 'images/image' + count + '.JPG';
            context.drawImage(img, 50, 60, 120, 151);
            timer = setTimeout(AnimateNow, 100);
            if (count == 8) {

        function StopAnimation() {
            count = 0;

        function ResetCanvas() {
            count = 0;
            context.clearRect(0, 0, canvas.width, canvas.height);

In the above JavaScript code snippet, under AnimateNow function, we are incrementing the value of count variable and loading the images whose names are in sequence (image1.jpg, image2.jpg, image3.jpg .... image8.jpg). All these images are being loaded at the interval of 100 millisconds.

In StopAnimation() and ResetAnimation() functions, we are setting the count variable value to 0. StopAnimation() function calls the clearTimeout(timer) function that stops the execution of the AnimateNow function under setTimeout() and ResetCanvas() function simply clears canvas.

For more details fo above functions, visit previous post.

 Views: 22589 | Post Order: 114

Write for us

Hosting Recommendations