简体   繁体   中英

Canvas Clear not working; Array items dont get deleted

The squares still get drawn even tough they are deleted from the array that is drawn. Shouldn't they be deleted when they are being deleted from the Array. Does the array not update inside the go function?

Javascript:

var canvas;
var ctx;


$(document).ready(function(){

    $("#thebutton").on('click',function(){
        thearray.pop();
    })
    canvas = $('#canvas').get(0);
    ctx =canvas.getContext("2d");
})

class Square{
    constructor(p1,p2,p3,p4){
        this.p1=p1;
        this.p2=p2;
        this.p3=p3;
        this.p4=p4;
    }
    start(){
        var that = this;
        setTimeout(function(){
            that.go();
            that.start();
            console.log("timeout running");

        },1000);
    }
    go(){

       for(let i = 0; i<thearray.length;i++){
           console.log("loop running:"+i);
            if(true){
                ctx.clearRect(0,0,500,500);
                console.log("clearing rect");
            }
            ctx.rect(thearray[i].p1, thearray[i].p2, thearray[i].p3, thearray[i].p4);
            ctx.stroke();
      }
    }
}

var thearray=[];
var thesquare1 = new Square(20,20,150,100);
var thesquare2 = new Square(100,100,200,200);
var thesquare3 = new Square(200,200,300,300);
thearray.push(thesquare1);
thearray.push(thesquare2);
thearray.push(thesquare3);

thesquare1.start();

HTML:

<canvas id="canvas" height="500" width="500"></canvas>
<button type="button" name="button" id="thebutton">Pop Array</button>

Spent almost an hour on debugging your code! This led to the finding that if fillRect() is used instead of rect() the code works well... and then finally found this.. (I too didn't know it before ><) Have a look at this: link


In short, just call beginPath() after clearRect() to start a new path instead of using old path stack!!!

go(){

   ctx.clearRect(0,0,500,500);
   ctx.beginPath(); //This line saved the day :)))
   console.log("clearing rect");

   for(let i = 0; i<thearray.length;i++) {
       console.log("loop running:"+i);
        ctx.rect(thearray[i].p1, thearray[i].p2, thearray[i].p3, thearray[i].p4);
        ctx.stroke();
    }
}

using this the code works for rect() as intended :)

Note: also you have to move that clearRect() call outside the for loop otherwise it will clear the canvas after every single iteration of the loop which results in showing only the 3rd rectangle on the canvas. Also, that if(true){} is not at all necessary.

Update: Also checkout this thread for some other alternatives to beginPath() to handle such scenario

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.

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