1 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
問題是某些變量是在函數(shù)外部定義的,initCanvas因此在所有組件(line1、和)之間共享。因此,每次您調(diào)用時(shí),它們都會(huì)被覆蓋。line2ctxcanvasEleminitCanvas
一個(gè)快速的解決方案是將其包裝在一個(gè)類中:
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();
}
}
然后在組件中實(shí)例化它:
componentDidLoad() {
let canvas = this.el.querySelector('canvas');
const waveCanvas = new WaveCanvas(canvas);
waveCanvas.init();
waveCanvas.animate();
}
這樣, 的每個(gè)實(shí)例都WaveCanvas將擁有自己對正確<canvas>元素的引用。
添加回答
舉報(bào)