在我的画布上,我有两种类型的圆圈:
我直接从上下文中创建的那些(= decoratingStars):
drawDecorativeStar = (decorativeStar) => {
this.ctx.beginPath();
this.ctx.arc(decorativeStar.x, decorativeStar.y, decorativeStar.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = "rgba(254, 255, 242," + decorativeStar.alpha + ")";
this.ctx.fill();
this.ctx.closePath();
}
以及那些创建为 Path2D 的,因为我希望它们是可点击的(=planetPaths):
createPlanetPaths = (planets) => {
for (var i = 0; i < planets.length; i++) {
this.planetPaths[i] = {
ref: new Path2D(),
x: Math.random() * WIDTH_CANVAS,
y: Math.random() * HEIGHT_CANVAS,
radius: this.getPlanetRadius(planets[i]),
color: planets[i].color,
}
}
}
drawPlanets = (planetPaths) => {
for (let i = 0; i < planetPaths.length; i++) {
planetPaths[i].ref.arc(planetPaths[i].x, planetPaths[i].y, planetPaths[i].radius, 0, 2 * Math.PI);
planetPaths[i].ref.gradient = this.ctx.createLinearGradient((planetPaths[i].x - planetPaths[i].radius), (planetPaths[i].y - planetPaths[i].radius), 1.02 * (planetPaths[i].x + planetPaths[i].radius), 1.02 * (planetPaths[i].y + planetPaths[i].radius));
planetPaths[i].ref.gradient.addColorStop(0, planetPaths[i].color);
planetPaths[i].ref.gradient.addColorStop(1, 'red');
this.ctx.fillStyle = planetPaths[i].ref.gradient;
this.ctx.fill(planetPaths[i].ref);
}
};
现在我想使用 requestAnimationFrame 为这些圆圈设置动画。我的问题是这this.ctx.clearRect(0, 0, WIDTH_CANVAS, HEIGHT_CANVAS);
似乎对 Path2D 对象没有影响,而它对其他对象有效。
还有另一种清除 Path2D 对象的方法吗?
编辑,这里是我的 updateCanvas 方法,以生成动画:
updateCanvas() {
this.ctx.clearRect(0, 0, WIDTH_CANVAS, HEIGHT_CANVAS);
for (let i = 0; i < this.planetPaths.length; i++) {
var planetPath = this.planetPaths[i];
if (planetPath.x < WIDTH_CANVAS) {
planetPath.x += 1;
} else {
planetPath.x = 0;
}
}
for (let i = 0; i < this.decorativeStars.length; i++) {
var star = this.decorativeStars[i];
if (star.decreasing == true) {
star.alpha -= star.decreasingIncreasingRatio;
if (star.alpha < 0.10) { star.decreasing = false; }
}
else {
star.alpha += star.decreasingIncreasingRatio;
if (star.alpha > 0.95) { star.decreasing = true; }
}
// star.x+=0.01;
}
this.drawDecorativeStars(this.decorativeStars);
this.drawPlanets(this.planetPaths);
this.myReq = requestAnimationFrame(this.updateCanvas);
}