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

HTML Code

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

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

JavaScript code

<script>
        var canvas;
        var context;
        var photo;
        var timer;
        var count = 0;

        function StartAnimation() {

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

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

        function StopAnimation() {
            count = 0;
            clearTimeout(timer);
        }

        function ResetCanvas() {
            count = 0;
            context.clearRect(0, 0, canvas.width, canvas.height);
        }
    </script>

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: 1559 | Post Order: 113



Write for us