How to clear a circle drawn with arc in javascript?

时间:2019-03-19 14:49:00

标签: javascript html5-canvas

I am having problems when drawing a circle. How do I clear it? I also still want to maintain the transparent background as much as possible as I am planning on making particles rain down. I also would want to not use images to lower the load on the server.

var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");

const ParticleFactory = function(){
    this.interval = 100;
    this.lastOutput = Date.now();
    this.particles = [];
}

ParticleFactory.prototype.tick = function(){
    if (Date.now() > this.lastOutput + this.interval) {
        const particle = new Particle(500, 100, 4);
        this.particles.push(particle);
        this.lastOutput = Date.now();
    }
    for (var i=0; i < this.particles.length; i++) {
        this.particles[i].tick();
    };
}
ParticleFactory.prototype.draw = function(){
    for (var i=0; i < this.particles.length; i++) {
        this.particles[i].draw();
    };
}
ParticleFactory.prototype.del = function(toDelete){
    this.particles = this.particles.filter(item => item !== toDelete);
}
const Particle = function(x, y, r){
    this.x = x;
    this.y = y;
    this.r = r;
}

Particle.prototype.tick = function(){
    this.x -= 0.1;
}
Particle.prototype.draw = function(){

    ctx.beginPath();
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
    ctx.fillStyle = "rgb(0, 0, 255)";
    ctx.fill();
    ctx.closePath();
}
// Definitions
let particleFactory = new ParticleFactory;

function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    particleFactory.draw();

}
function tick(){
    particleFactory.tick();

    draw()
    window.requestAnimationFrame(tick)
}

document.addEventListener("DOMContentLoaded", function() {
    tick();
});

ctx.clearRect() doesn't clear the curcle that is being draws every tick by Particle.draw()

The dot moves and leaves a trail behind even when ctx.clearRect() is run before every draw.

0 个答案:

没有答案