【发布时间】:2019-12-29 01:45:51
【问题描述】:
我看到您可以使用CanvasRenderingContext2D.clearRect 清除部分画布。此功能将根据指定的坐标清除全部/部分画布。是否可以清除一些前景图,但保持背景图完整?
在反应组件内部,我有以下内容
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();
}
问题是动画重复后所有的星星都不会消失。有没有办法只清理星星的画,但保留backgroundGradient,或者两张画总是必须同时清理,因为它们位于同一个画布上?
总的来说,我正在尝试创建这些星星的闪烁效果。当我每次都需要清理/重绘整个画布来模拟每颗星星的闪烁时,这似乎是很多开销。
[编辑]
- 为了优化动画效果,您可以将 2 个单独的画布绘制为 HERE
【问题讨论】:
-
是的,这很有帮助,我会更新我的问题。是否可以只更新星星的不透明度,而不是重新绘制所有星星?
-
很遗憾没有。画布上的任何东西一旦被绘制就不可能更新。您所能做的就是擦除一个部分或在其上绘制。
-
我会继续将这些 cmets 移动到答案中,因为它们似乎已经帮助您解决了您的问题。
-
是的,我没问题。谢谢!