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

293
Visualizações
How to use constructors and images in javascript?

I have the following segment of code intented to draw an image onto the canvas. This code works:

var ctx = canvas.getContext('2d');

class Rectangle {
    constructor(x, y, scale, source) {
        this.scale = scale;
        this.source = source;
        this.x = x;
        this.y = y;
    }

    update() {
        var sprite = new Image();
        sprite.src = this.source;
        sprite.onload = function () {
            ctx.drawImage(sprite, this.x, this.y, sprite.width/3, sprite.height/3);
        }
    }
}

const rect = new Rectangle(0, 0, 1, 'circle.jpeg');
rect.update();

But, when I replace this line:

ctx.drawImage(sprite, this.x, this.y, sprite.width/3, sprite.height/3);

with this:

ctx.drawImage(sprite, this.x, this.y, sprite.width/this.scale, sprite.height/this.scale);

the canvas doesn't show anything at all. All this should be doing is replacing the 3 from before with the value from the constructor (which I set to 1 when I create a new instance). Why isn't it drawing anything?

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

0

I would move the sprite to the constructor that way when we call the update we don't have to create a new image, the idea behind that is the update function could be called multiple times efficiently.

See this sample below:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

class Rectangle {
  constructor(x, y, scale, source) {
    this.scale = scale;
    this.x = x;
    this.y = y;
    this.sprite = new Image();
    this.sprite.src = source;
    this.sprite.onload = () => {
      this.update()
    };
  }

  update() {
    if (this.sprite) {
      ctx.drawImage(this.sprite, this.x, this.y, this.sprite.width / this.scale, this.sprite.height / this.scale);
    }
  }
}

const rect = new Rectangle(0, 0, 3, 'http://i.stack.imgur.com/UFBxY.png');

canvas.addEventListener("click", () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  rect.x += 5;
  rect.update();
});
<canvas id="canvas"></canvas>

You can see that as suggested in the comments by @skara9 I'm using the () => instead of function() and I'm calling the update there.

On this sample I also added canvas.addEventListener("click" that shows how when the user clicks on the canvas the drawing move a little to the right, the logic is simple we increase the value of rect.x and then we call the rect.update(); that will draw the image on the new location.

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