1
    <!DOCTYPE html>
<head>
    <meta charset="UTF-8" />
    <title>Animating Sprites In HTML5 Canvas | onlyWebPro.com</title>
</head>
<body>
    <canvas id="myCanvas" width="100" height="100">
        <!-- Insert fallback content here -->
        Sorry, your browser doesn't support canvas technology
    </canvas>
    <script>
    var width = 100,
            height = 100,
            frames = 4,

            currentFrame = 0,

            canvas = document.getElementById("myCanvas");
            ctx = canvas.getContext("2d");
            image = new Image()
            image.src = 'sprite.png';

    var draw = function(){
            ctx.clearRect(0, 0, width, height);
            ctx.drawImage(image, 0, height * currentFrame, width, height, 0, 0, width, height);

            if (currentFrame == frames) {
              currentFrame = 0;
            } else {
              currentFrame++;
            }
    }

    setInterval(draw, 100);
    </script>
</body>
</html>

The above is the code for creating a canvas which runs a sprite animation sequence in canvas.

Now I want to include another canvas image in same html. when i tried the old one gets replaced so please help me to create another canvas with another image.

Anyone solve it by providing a way to create a multiple canvas in a single HTML page

1
  • 4
    just add another canvas, give it a different id, do the samething. Commented Jul 20, 2013 at 9:59

1 Answer 1

1

Add this at html part:

<canvas id="mySecondCanvas" width="100" height="100">
        <!-- Insert fallback content here -->
        Sorry, your browser still doesn't support canvas technology
    </canvas>

And this how you get this canvas with javascript:

var second_canvas = document.getElementById("mySecondCanvas");

:)

Sign up to request clarification or add additional context in comments.

1 Comment

Just don't put anything inside the second <canvas> tag - why would you tell the user about non-support twice?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.