Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

292
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda