gpt4 book ai didi

javascript - clearRect() 的工作方式很奇怪

转载 作者:行者123 更新时间:2023-11-28 18:52:22 24 4
gpt4 key购买 nike

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

<!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(); code> 和 ctx.lines(); 在一个方法中。

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>

关于javascript - clearRect() 的工作方式很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34291366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com