clearRect()工作奇怪

时间:2015-12-15 14:10:43

标签: javascript html5 html5-canvas

ClearRect以奇怪的方式工作;我试图刷新画布,但它不适用于此代码

<!DOCTYPE html>
<html>
    <head>
        <title> Crypt </title>
    </head>
    <body>
        <canvas id="canvas" width="500" height="300" style="border-style: dashed;"></canvas>
        <script type="text/javascript">
        var can     =   document.getElementById("canvas")               ,
            ctx     =   can.getContext("2d")                            ,
            posX    =   0                                               ,
            posY    =   0                                               ;

        function game(){ // HERE
            ctx.clearRect(0, 0, can.width, can.height);
            ctx.rect(posX, posY, 20, 20);
            ctx.stroke();

            posX += 10;
            posY += 10;
        }

        window.setInterval("game()", 100);
        </script>
    </body>
</html>

完美搭配:

<!DOCTYPE html>
<html>
    <head>
        <title> Crypt </title>
    </head>
    <body>
        <canvas id="canvas" width="500" height="300" style="border-style: dashed;"></canvas>
        <script type="text/javascript">
        var can     =   document.getElementById("canvas")               ,
            ctx     =   can.getContext("2d")                            ,
            posX    =   0                                               ,
            posY    =   0                                               ;

        function game(){    // HERE
            ctx.clearRect(0, 0, can.width, can.height);
            ctx.strokeRect(posX, posY, 20, 20);

            posX += 10;
            posY += 10;
        }

        window.setInterval("game()", 100);
        </script>
    </body>
</html>

有人能够解释吗?谢谢 我真的不明白javascript是如何工作的,所以如果你有一些讲座,我会接受它

谢谢^ 2

1 个答案:

答案 0 :(得分:3)

您面临的问题不在于clearRect(),而在于您始终在同一个Path对象上调用ctx.rect()

为避免这种情况,您必须在每张新图纸上致电ctx.beginPath()

var can = document.getElementById("canvas"),
  ctx = can.getContext("2d"),
  posX = 0,
  posY = 0;

function game() {
  ctx.clearRect(0, 0, can.width, can.height);

  // create a new Path2d
  ctx.beginPath();

  ctx.rect(posX, posY, 20, 20);
  ctx.stroke();

  posX += 10;
  posY += 10;
}

window.setInterval(game, 100);
<canvas id="canvas" width="500" height="300" style="border-style: dashed;"></canvas>

或者,您可以拨打ctx.strokeRect(),在单个方法中处理ctx.beginPath();ctx.rect();ctx.stroke();

var can = document.getElementById("canvas"),
  ctx = can.getContext("2d"),
  posX = 0,
  posY = 0;

function game() { // HERE
  ctx.clearRect(0, 0, can.width, can.height);

  ctx.strokeRect(posX, posY, 20, 20);

  posX += 10;
  posY += 10;
}

window.setInterval(game, 100);
<canvas id="canvas" width="500" height="300" style="border-style: dashed;"></canvas>