在canvas功能中查询问题

时间:2018-12-09 04:09:03

标签: javascript canvas html5-canvas

为什么它不能正常运行?单击该按钮时,该块完全不移动。最初,网站可以正常运行,但是在几次更改块大小后,网站突然无法运行。有人可以帮我解决问题吗?非常感谢!

<!DOCTYPE html>
<html>
<head> 
<style>
canvas{border:1px solid black;)
</style>
<script>
var canvas;
var ctx;
var rect_x=0;
var rect_y=0;
function animate()
{
  ctx.clearRect(0,0,canvas.width,canvas.height);
  rect_y+=5;
  canvas = document.getElementById("Mycanvas");
  ctx = canvas.getContext("2d");
  ctx.fillStyle="red";
  ctx.fillRect(rect_x,rect_y,50,50); 
  if (rect_y>=canvas.height-50);
  {clearInterval(timer);}
}
function draw()
{
  rect_x = 0;
  rect_y = 0;
  canvas = document.getElementById("Mycanvas");
  ctx = canvas.getContext("2d");

  timer = setInterval("animate()",50);
}
</script>
</head>
<body>
<canvas id="Mycanvas" width="200" height="300"></canvas>
<br/>
<button onclick="draw()"> Draw</button>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

错字,您在if()情况下出现分号

if (rect_y>=canvas.height-50);

这等于“如果rect_y >= canvas.height - 50不执行任何操作”

if (rect_y >= canvas.height - 50)
    ;

,这意味着您的下一个区块{clearInterval(timer);}将始终被调用。

<!DOCTYPE html>
<html>
<head> 
<style>
canvas{border:1px solid black;)
</style>
<script>
var canvas;
var ctx;
var rect_x=0;
var rect_y=0;
function animate()
{
  ctx.clearRect(0,0,canvas.width,canvas.height);
  rect_y += 5;
  canvas = document.getElementById("Mycanvas");
  ctx = canvas.getContext("2d");
  ctx.fillStyle = "red";
  ctx.fillRect(rect_x,rect_y,50,50); 
  if (rect_y>=canvas.height-50) {
    clearInterval(timer);
  }
}
function draw()
{
  rect_x = 0;
  rect_y = 0;
  canvas = document.getElementById("Mycanvas");
  ctx = canvas.getContext("2d");

  timer = setInterval("animate()",50);
}
</script>
</head>
<body>
<canvas id="Mycanvas" width="200" height="300"></canvas>
<br/>
<button onclick="draw()"> Draw</button>
</body>
</html>

但是请注意,从

开始,关于您的代码还有很多话要说
  • 请勿将setInterval用于视觉动画,而总是偏爱requestAnimationFrame
  • 此外,切勿像setInterval("someFunc()", t)那样隐式使用邪恶的eval,而应像setInterval(someFunc, t)那样直接将对回调的引用传递给回调。
  • 在清除setInterval超时之前,绝不要覆盖它。使用当前代码,如果在满足条件之前单击几次,将运行多个setIntervals,直到页面消失。

答案 1 :(得分:0)

您应该始终努力使代码可扩展和可重用,同时使代码尽可能清晰和简单。像下面这样的错误可以解决。

<!DOCTYPE html>
<head></head>
<body>
<canvas id="Mycanvas" width="500" height="500" style="border:1px solid #000000;">
</canvas> 
<script>
var c=document.getElementById("Mycanvas");
var ctx=c.getContext("2d");
var rect_x=0;
var rect_y=0;
var rectHeight = c.height/10;
var rectWidth = c.width/10;

function animate(){
ctx.clearRect(0,0,c.width,c.height);
drawNew();
if (rect_y+5<=c.height-rectHeight){
rect_y+=5;}
}

function drawNew(){
ctx.beginPath();
ctx.rect(rect_x, rect_y, rectWidth, rectHeight);
ctx.fillStyle = "red";
ctx.fill();
}

setInterval(animate,50); 

</script>
</body></html>