1 回答
TA贡献1831条经验 获得超4个赞
问题是某些变量是在函数外部定义的,initCanvas因此在所有组件(line1、和)之间共享。因此,每次您调用时,它们都会被覆盖。line2ctxcanvasEleminitCanvas
一个快速的解决方案是将其包装在一个类中:
export class WaveCanvas {
constructor(canvas) {
this.canvasElem = canvas;
this.ctx = canvas.getContext("2d");
const parent = canvas.parentElement;
canvas.width = parent.clientWidth;
canvas.height = parent.scrollHeight;
}
init() {
// ...
this.line1 = new Line(...);
}
animate() {
requestAnimationFrame(() => this.animate());
this.ctx.clearRect(0, 0, this.canvasElem.width, this.canvasElem.height);
this.line1.update();
this.line2.update();
}
}
然后在组件中实例化它:
componentDidLoad() {
let canvas = this.el.querySelector('canvas');
const waveCanvas = new WaveCanvas(canvas);
waveCanvas.init();
waveCanvas.animate();
}
这样, 的每个实例都WaveCanvas将拥有自己对正确<canvas>元素的引用。
添加回答
举报