在 javascript 中向画布添加方法和字段的正确编程模式

问题描述 投票:0回答:1

我想创建一个用js管理的html画布类,以便通过拖放拖放Path2D、缩放和翻译,以便一切都在类而不是实例上干净地完成。 Canvas 不是一个类,不能扩展。触摸它的原型似乎非常粗略,特别是在搜索了 SO 之后。

理想的东西看起来像

class MyCanvas extends canvas {
constructor() {
    this.2DShapes= [];
    this.addEventListener('mousedown', this.onmousedown, false);
    ...
}

add2DShape(name, x, y, angle = 0, strokeStyle, fillStyle, lineWidth ) {
    let shape = new 2DShape(name, x, y, angle, strokeStyle, fillStyle, lineWidth);
    this.2DShapes.push(shape);
    this.draw();
}
draw() {
    let ctx = this.getContext("2d");
    
    for(let shape of this.2DShapes) {
        ctx.save();
        // draw shape with rotation zoom whatever
        ctx.restore();
    }
}

但是这是不可能的,我能管理的最好的方法就是向我的类添加一个canvas成员,然后各种输入/输出函数不再是该类的一部分,而是属于它的canvas成员(onmouse、draw、 ...).

“扩展”画布功能并使其成为画布的一部分的正确模式是什么?或者是拥有容器类的唯一选择?

感谢您的关注:)

javascript class canvas
1个回答
0
投票

这是一个复杂的问题,因为你无法扩展

HTMLCanvasElement
。你只会得到非法调用错误。

试试这个方法:

// Do not extends HTMLCanvasElement
class MyCanvas
{
  constructor ()
  {
    // Create the object that will be returned: a HTMLCanvasElement object.
    const newCanvas = document.createElement('canvas');
    
    // Assign the prototype properties/methods to the new canvas element.
    Object.defineProperties(newCanvas, Object.getOwnPropertyDescriptors(MyCanvas.prototype));
    
    // Do everything else over newCanvas instead of this in the constructor.
    
    newCanvas.ctx = newCanvas.getContext('2d');
    
    // Directly return the newCanvas instead of a MyCanvas object.
    return newCanvas;
  }
  
  draw ()
  {
    // Draw is overriden.
    console.log('Drawing, but not!');
    console.log('Context:', this.ctx);
  }
}

const myCanvas = new MyCanvas;

myCanvas.draw();

PS:这只是一个最小的复制品。您必须以您喜欢的方式完成课程。

© www.soinside.com 2019 - 2024. All rights reserved.