1

我想用javascript和html画布制作动画,只是让一个矩形从窗口顶部移动到底部,我使用canvas.clearRect清除画布上的所有像素,但是,这个函数似乎没有工作,之前的图纸还在。这是所有的代码

<!DOCTYPE HTML>
<html>
    <title>Jave script tetris by zdd</title>
    <head>
        <script>
            function point(x, y)
            {
                this.x = x;
                this.y = y;
            }

            function draw(timeDelta)
            {
                // Vertices to draw a square
                var v1 = new point(  0,   0);
                var v2 = new point(100,   0);
                var v3 = new point(100, 100);
                var v4 = new point(  0, 100);
                this.vertices = [v1, v2, v3, v4];

                // Get canvas context
                var c = document.getElementById("canvas");
                var cxt = c.getContext("2d");

                // Clear the canvas, this does not work?
                cxt.clearRect(0, 0, 800, 600);

                // Move the piece based on time elapsed, just simply increase the y-coordinate here
                for (var i = 0; i < this.vertices.length; ++i)
                {
                    this.vertices[i].y += timeDelta;
                }

                cxt.moveTo(this.vertices[0].x, this.vertices[0].y);
                for (var i = 1; i < this.vertices.length; ++i)
                {
                    cxt.lineTo(this.vertices[i].x, this.vertices[i].y);
                }
                cxt.lineTo(this.vertices[0].x, this.vertices[0].y);
                cxt.stroke();
            }

            var lastTime = Date.now();
            function mainLoop()
            {
                window.requestAnimationFrame = window.requestAnimationFrame || 
                                               window.mozRequestAnimationFrame ||
                                               window.webkitRequestAnimationFrame || 
                                               window.msRequestAnimationFrame;
                window.requestAnimationFrame(mainLoop);

                var currentTime = Date.now();
                var timeDelta = (currentTime - lastTime);
                draw(timeDelta);
                lastTime = currentTime;
            }

        </script>
    </head>
    <body>
        <canvas id="canvas" width="800" height="600">
        </canvas>
        <script>
        </script>
        <button type="button" style="position:absolute; left:500px; top:600px; width:100px; height:50px;" class="start" onclick="mainLoop()">start</button>
    </body>
</html>

这是 Chrome 中的结果图片,我只想要一个矩形,但是 clearRect 函数没有清除旧的矩形,所以......,如何解决这个问题? 在此处输入图像描述

4

1 回答 1

2

你失踪了beginPath。没有它,每个盒子实际上都是最后一个盒子的一部分。

    cxt.beginPath();
    cxt.moveTo(this.vertices[0].x, this.vertices[0].y);

    for (var i = 1; i < this.vertices.length; ++i) {
        cxt.lineTo(this.vertices[i].x, this.vertices[i].y);
    }

添加之后,盒子似乎在晃动,不确定这是否是您的意图。

这是一个小提琴:http: //jsfiddle.net/6xbQN/

祝你好运!

于 2012-12-12T15:21:09.337 回答