Tengo este código y siempre tengo que crear el const ctx al comienzo del documento con el mismo nombre utilizado en la clase, y me pregunto si tengo alguna forma de hacer que esta clase sea más portátil para otros proyectos.
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); } }Simplemente exporte su clase y haga que su clase tome un contexto en el 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); } }Ahora cualquiera que use tu clase puede importarla:
import { Layer } from './layer.js';Y el usuario de la clase tiene que obtener el contexto del lienzo. Sin embargo, pueden obtenerlo una vez y pasarlo a tantas capas como quieran:
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);No hay nada más que puedas hacer más allá de eso.