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

98
Visualizações
how to make JavaScript class portable for any project

I have this code and I always have to creat the const ctx at begin of document with same name used in the class, and I wonder if have way make this class more portable for others project

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');

class layer{
    constructor(image, speedModifier){
        this.x = 0;
        this.y = 0;
        this.width = 2400;
        this.height = 700;
        //this.x2 = this.width;
        this.image = image;
        this.speedModifier = speedModifier;
        this.speed = gameSpeed * this.speedModifier
    }
    update(){
        this.speed = gameSpeed * this.speedModifier;
        this.x = gameFrame * this.speed % this.width;
    }
    draw(){
        ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
        ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just export your class and make your class take in a context in the constructor.

export class Layer {
  constructor(image, speedModifier, context) {
    this.context = context;
    this.x = 0;
    this.y = 0;
    this.width = 2400;
    this.height = 700;
    this.image = image;
    this.speedModifier = speedModifier;
    this.speed = gameSpeed * this.speedModifier
  }

  draw(){
    this.context.drawImage(this.image, this.x, this.y, this.width, this.height);
    this.context.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
  }
}

Now anyone who uses your class can import it:

import { Layer } from './layer.js';

And the user of the class has to get the canvas context. However they can then get that once and pass it in to as many layers as they want:

const context = document.querySelector('canvas').getContext('2d');
const layer1 = new Layer(someImage, 1, context);
const layer2 = new Layer(anotherImage, 1, context);
const layer3 = new Layer(thirdImage, 2, context);

Nothing more you can really do beyond that.

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