Ricki Moore Ricki Moore - 2 months ago 16
Javascript Question

HTML5 Canvas clearRect not working with beginPath and closePath

Im using HTML5 to draw on canvas. I have an array of points in which i loop through to change the x and y coordinates each cycle of draw. What i have now is the dots moving but not clearing the old one, so just lines moving across instead of dots. I looked up other answers which said that i need to use the beginPath with clearRect but that doesn't work. Is there something wrong with the placement of the clearRect can someone help me with this canvas stuff.

draw: function () {
var ctx = this.context;
if(this.isReady){
var PI2 = Math.PI * 2;
for (var i = 0; i < this.points.length; i++) {
var point = this.points[i];
var ic = this.calculateGravity(point.x, point.y);
ctx.clearRect(0, 0, this.cw, this.ch);
ctx.beginPath();
ctx.arc(point.x - ic.nX, point.y - ic.nY, point.radius, 0, PI2);
ctx.fillStyle= point.color;
ctx.strokeStyle= point.color;
ctx.closePath();
ctx.fill();
ctx.stroke();
this.points[i].x = point.x - ic.nX;
this.points[i].y = point.y - ic.nY;
}
}
},

Answer

You should clear your canvas just before rendering your points:

if(this.isReady){
    ctx.clearRect(0, 0, this.cw, this.ch);
    var PI2 = Math.PI * 2;
    for (var i = 0; i < this.points.length; i++) {
    /* ... */
}