Kyle Thompson Kyle Thompson - 1 month ago 8
Javascript Question

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. 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>




Answer

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);