2 回答
TA贡献1780条经验 获得超1个赞
如果您的仪表变量t1,...,t10被定义为全局变量,那么您可以window['t'+i]在for循环中处理它们i。
但是@Helder Sepulveda 建议将它们保存在一个通用的数组对象 ( gauges) 中,因为这样可以避免名称冲突。
TA贡献1860条经验 获得超9个赞
您应该使用数组:
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>
添加回答
举报
