gpt4 book ai didi

javascript - clearRect 不清除

转载 作者:行者123 更新时间:2023-11-30 12:39:06 24 4
gpt4 key购买 nike

所以我每秒做一个正方形,沿着页面慢慢移动。然后我调用 clearRect 来清除 Canvas ,这样旧的方 block 就会被移除,只剩下新的方 block ,但我做错了什么, Canvas 没有被清除。

  • 如何让 clearRect 清除旧方 block ?

我读过的之前的问题围绕着使用“draw()”,但我没有使用它。

HTML

<canvas id="canv1" width="100px" height="100px"></canvas>
<input id="counter" style="width:40px;"></input>

JS

i = 1;
c=1;

window.onload=function(){
hello();
}

function hello(){
setInterval(function(){func()},1000);
}

function func(){
var x = document.getElementById("counter");
x.value = c;
var d = document.getElementById("canv1");
var ctx = d.getContext("2d");
ctx.rect(20+c,20,40,40);
ctx.clearRect(0,0,100,100);
ctx.stroke();
c++
}

http://jsfiddle.net/ys9Yk/1/

最佳答案

你可以使用strokeRect:

setInterval(func, 1000);

var x = document.getElementById("counter");
var d = document.getElementById("canv1");
var ctx = d.getContext("2d");
var i = 1;
var c = 1;

function func() {
x.value = c;
ctx.clearRect(0, 0, 100, 100);
ctx.strokeRect(20 + c, 20, 40, 40);
c++;
}

演示: http://jsfiddle.net/ys9Yk/6/

关于javascript - clearRect 不清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102944/

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