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. 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.