Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Accesing to canvas as property from class works only for second object

I'am working on simulation of train station control panel. I created canvas with map of station and interactive elements. I decided to create class with signals for trains to save lines of code. It looks like this:

class enterSignal{
    constructor(status, position, x, y, canvas){ //status and position are not used yet
        this.ctx1 = canvas.getContext('2d');
        this.ctx1.beginPath();
        this.ctx1.arc(x, y, 5, 0, 2 * Math.PI);
        this.ctx1.fillStyle = "rgb(109, 109, 109)";
        this.ctx1.fill();
    } 
    goAhead(){
        this.ctx1.fillStyle = 'green';
        this.ctx1.fill();
    }
}

The goAhead() method changes color of ctx1 canvas to green (go ahead signal for train driver). The main problem is when I create two objects of enterSignal class and run goAhead() method for single object it works only for last object. For example:

var enterSignal1 = new enterSignal("red", "left", 50, 190, canvas);
var enterSignal2 = new enterSignal("red", "right", 930, 150, canvas);
enterSignal1.goAhead();

It affects on enterSignal2 instead of enterSignal1.

So where is the problem?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here is another way...
just like they mentioned in the comments, we re-draw the element.

class enterSignal {
  constructor(color, x, y, canvas) {
    this.ctx1 = canvas.getContext('2d');
    this.x = x
    this.y = y
    this.draw(color)
  }
  draw(color) {
    this.ctx1.beginPath();
    this.ctx1.arc(this.x, this.y, 8, 0, 2 * Math.PI);
    this.ctx1.fillStyle = color;
    this.ctx1.fill();
  }
}

const canvas = document.getElementById("c");
var enterSignal1 = new enterSignal("red", 10, 10, canvas);
var enterSignal2 = new enterSignal("red", 20, 30, canvas);
var enterSignal3 = new enterSignal("red", 30, 50, canvas);
enterSignal1.draw("green");
enterSignal2.draw("yellow");
<canvas id="c"></canvas> 

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda