I see you can clear part of the canvas using CanvasRenderingContext2D.clearRect. This function will clear up full/partial canvas based on the coordinates specified. Is it possible to clear some of the foreground drawings, but keep the background drawings intact?
Inside of react component, I have the following
componentDidMount() {
this.canvas = this.canvasRef.current;
this.c = this.canvas.getContext('2d')
this.canvas.width = window.innerWidth
this.canvas.height = window.innerHeight
window.addEventListener('resize', this.resize)
this.init()
this.backgroundGradientAnimate() //draw background gradient
window.requestAnimationFrame(this.step)
}
// generate stars
init = () => {
this.stars = []
for (let i = 0; i < 150; i++) {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height
const r = Math.random() * 3
this.stars.push(new Star(x, y, r, 'white'))
}
}
draw = (star) => {
this.c.save()
this.c.beginPath()
this.c.arc(star.x, star.y, star.radius, 0, Math.PI * 2, false)
this.c.fillStyle = this.getRandomColor()
this.c.fill();
this.c.closePath();
this.c.restore()
}
starsAnmiate = () => {
this.stars.forEach(star => this.draw(star))
}
// only animate in such time
step = (elapsedTime) => {
let delta = elapsedTime - this.lastFrameTime || 0
window.requestAnimationFrame(this.step)
if (this.lastFrameTime && delta < 1000) {
return;
}
this.lastFrameTime = elapsedTime
this.starsAnmiate();
}
The issue is that all the stars never cleared out after animations repeat itself. Is there way of only cleaning up the drawing of stars but retaining the backgroundGradient
, or two drawings always have to be cleaned at the same time because they sit on the same canvas?
Overall, I'm trying to create a blinking effect of those stars. It just seems to be lots of overhead when I need to clean/redraw the entire canvas every time to simulate the blinking of each star.
[EDIT]
- To optimize animation effort, you can draw 2 separate canvas as HERE