clearRect()的工作原理很奇怪

clearRect() works strangely

本文关键字:工作 clearRect      更新时间:2023-09-26

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

您面临的问题不是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>