简体   繁体   English

HTML5 Canvas clearRect不起作用

[英]HTML5 Canvas clearRect isn't working

So I'm trying to have an 'X' appear on the screen and go across every second, but the previous 'X's don't go away when I draw the new ones, a whole path of 'X's stays behind and I want it to just be one that moves across in 60px increments. 所以我试图让屏幕上出现一个“X”并且每秒钟都会出现,但是当我绘制新的X时,之前的'X'不会消失,整个路径'X'留在后面我想要它只是一个以60px为增量移动的人。 Obviously there must be something having to do with paths and such that I don't know about, here's my code: 显然必须有一些与路径有关的东西,我不知道,这是我的代码:

 //ctx is already defined as the canvas context and works fine var bx = 0; var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); setInterval(function(){ ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx.moveTo(bx*60 ,0); ctx.lineTo(bx*60+60,60); ctx.moveTo(bx*60+60,0); ctx.lineTo(bx*60 ,60); ctx.stroke(); bx++; },1000); 
  <canvas id="myCanvas" width="200" height="100"></canvas> 

You forget to begin and close path. 你忘了开始和关闭路径。 Your canvas go to clear but all your lines will be every iteration rerendered. 你的画布会清除,但你所有的线都将被重新渲染。

//ctx is already defined as the canvas context and works fine
var bx = 0;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
setInterval(function(){
    ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height);
    ctx.beginPath(); // begin
    ctx.moveTo(bx*60   ,0);
    ctx.lineTo(bx*60+60,60);
    ctx.moveTo(bx*60+60,0);
    ctx.lineTo(bx*60   ,60);
    ctx.closePath(); // close
    ctx.stroke();
    bx++;
},1000);

Try this: 尝试这个:

 //ctx is already defined as the canvas context and works fine var bx = 0; var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); setInterval(function() { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.beginPath(); ctx.moveTo(bx * 60, 0); ctx.lineTo(bx * 60 + 60, 60); ctx.moveTo(bx * 60 + 60, 0); ctx.lineTo(bx * 60, 60); ctx.closePath(); ctx.stroke(); bx++; }, 1000); 
 <canvas id="myCanvas" width="200" height="100"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM