慕码人2483693
您应该使用数组:gauges = []gauges.push(new RadialGauge(...))gauges.push(new RadialGauge(...))gauges.push(new RadialGauge(...))gauges.forEach(g => g.draw());//change the values latergauges.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>