2 回答

TA貢獻1780條經(jīng)驗 獲得超1個贊
如果您的儀表變量t1
,...,t10
被定義為全局變量,那么您可以window['t'+i]
在for
循環(huán)中處理它們i
。
但是@Helder Sepulveda 建議將它們保存在一個通用的數(shù)組對象 ( gauges
) 中,因為這樣可以避免名稱沖突。

TA貢獻1860條經(jīng)驗 獲得超9個贊
您應(yīng)該使用數(shù)組:
gauges = []
gauges.push(new RadialGauge(...))
gauges.push(new RadialGauge(...))
gauges.push(new RadialGauge(...))
gauges.forEach(g => g.draw());
//change the values later
gauges.forEach(g => {
var name = "t" + i;
...
g.value = 123;
});
這是一個完整的工作示例,說明它的外觀:
class RadialGauge {
constructor(ctx, x, y, color) {
this.ctx = ctx;
this.color = color;
this.x = x; this.y = y;
this.value = 0
}
draw() {
this.ctx.beginPath();
this.ctx.fillStyle = this.color;
this.ctx.arc(this.x, this.y, 22, 0, 2 * Math.PI);
this.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y)
var x = this.x + Math.sin(this.value/10) * 20;
var y = this.y + Math.cos(this.value/10) * 20;
this.ctx.lineTo(x, y)
this.ctx.stroke();
}
}
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
gauges = []
gauges.push(new RadialGauge(ctx, 50, 50, "red"))
gauges.push(new RadialGauge(ctx, 150, 50, "blue"))
gauges.push(new RadialGauge(ctx, 100, 100, "green"))
gauges.forEach(g => g.draw());
function reDraw() {
ctx.clearRect(0,0,400,400)
gauges.forEach(g => {
g.value++
g.draw()
});
}
setInterval(reDraw, 20);
<canvas id="c" width=400 height=150></canvas>
添加回答
舉報