Javascript clearRect()的工作原理很奇怪
ClearRect以一种奇怪的方式工作;我试图刷新画布,但这段代码不起作用Javascript clearRect()的工作原理很奇怪,javascript,html,html5-canvas,Javascript,Html,Html5 Canvas,ClearRect以一种奇怪的方式工作;我试图刷新画布,但这段代码不起作用 <!DOCTYPE html> <html> <head> <title> Crypt </title> </head> <body> <canvas id="canvas" width="500" height="300" style="border-style: dashe
<!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>
地穴
var can=document.getElementById(“画布”),
ctx=can.getContext(“2d”),
posX=0,
posY=0;
函数game(){//HERE
ctx.clearRect(0,0,罐宽,罐高);
ctx.rect(posX,posY,20,20);
ctx.stroke();
posX+=10;
posY+=10;
}
setInterval(“game()”,100);
与以下各项完美配合:
<!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>
地穴
var can=document.getElementById(“画布”),
ctx=can.getContext(“2d”),
posX=0,
posY=0;
函数game(){//HERE
ctx.clearRect(0,0,罐宽,罐高);
ctx.strokeRect(posX,posY,20,20);
posX+=10;
posY+=10;
}
setInterval(“game()”,100);
有人能解释吗?非常感谢。
我真的不明白javascript是如何工作的,所以如果你有一些讲座,我就接受了
谢谢^2您面临的问题不是
clearRect()
,而是您总是在同一路径对象上调用ctx.rect()
要避免这种情况,必须调用每个新图形:
var can=document.getElementById(“画布”),
ctx=can.getContext(“2d”),
posX=0,
posY=0;
函数游戏(){
ctx.clearRect(0,0,罐宽,罐高);
//创建新的Path2d
ctx.beginPath();
ctx.rect(posX,posY,20,20);
ctx.stroke();
posX+=10;
posY+=10;
}
设置间隔(游戏,100)代码>
您面临的问题不是clearRect()
的问题,而是您总是在同一路径对象上调用ctx.rect()
要避免这种情况,必须调用每个新图形:
var can=document.getElementById(“画布”),
ctx=can.getContext(“2d”),
posX=0,
posY=0;
函数游戏(){
ctx.clearRect(0,0,罐宽,罐高);
//创建新的Path2d
ctx.beginPath();
ctx.rect(posX,posY,20,20);
ctx.stroke();
posX+=10;
posY+=10;
}
设置间隔(游戏,100)代码>
什么不起作用?第一个代码示例不清除画布什么不起作用?第一个代码示例不清除画布