页面中的HTML5多个画布

时间:2013-07-20 09:56:55

标签: html canvas

    <!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>

以上是用于创建在画布中运行精灵动画序列的画布的代码。

现在我想在同一个html中包含另一个画布图像。当我尝试旧的一个被替换,所以请帮我创建另一个带有另一个图像的画布。

任何人都可以通过提供在单个HTML页面中创建多个画布的方法来解决它

1 个答案:

答案 0 :(得分:1)

在html部分添加:

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

这就是你如何用javascript获取这个画布:

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

:)