【问题标题】:how to make JavaScript class portable for any project如何使 JavaScript 类可移植到任何项目
【发布时间】:2021-10-23 11:28:26
【问题描述】:

我有这段代码,我总是必须在文档开头创建与类中使用的相同名称的 const ctx,我想知道是否有办法让这个类对其他项目更便携

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);
    }
}

【问题讨论】:

  • 将其创建为一个类,将其保存在单独的文件中,始终导出,导入您需要的文件并根据需要使用。

标签: javascript html jquery class object


【解决方案1】:

只需导出您的类并让您的类在构造函数中获取上下文。

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);
  }
}

现在任何使用你的类的人都可以导入它:

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

并且该类的用户必须获取画布上下文。然而,他们可以得到一次并将其传递到他们想要的任意多个层:

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);

除此之外,您无能为力。

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 2018-05-30
    • 1970-01-01
    • 2012-01-12
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2018-11-16
    相关资源
    最近更新 更多