1

I have many gauges declared as follows:

var g1 = new RadialGauge({
    renderTo: 'gauge1',
    width: 300,
    height: 300,
    units: 'Grados',
    title: "Temp_d9",
    valueBox: true,
    animationRule: 'bounce',
    animationDuration: 500
}).draw();

The names are g1..g2..g3..g10..

If I want to change the value of the gauge I do this:

g1.value = 10;

What I want to do , is change the value of all my gauges inside a for loop.. what I tried, and of course didnt work:

for(var i = 1; i <= 10 ; i ++){
    var name = "t" + i;
    name.value = lst_val;
}

How can I achieve this? it's possible? thanks

2 Answers2

0

You should be using arrays:

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;
});

Here is a full working example of how that might look like:

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>
Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
0

If your gauge variables t1, ... ,t10 are defined as global variables then you can address them as window['t'+i] inside your for loop over i.

But @Helder Sepulveda has a point when he suggests keeping them in a common array-object (gauges), as this avoids name collisions.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43