【问题标题】:resize read-only typed array调整只读类型数组的大小
【发布时间】:2018-04-12 06:37:45
【问题描述】:

我创建了自己的类,它扩展了ImageData 类,为我提供了更多操作和构造图像数据的方法:

class ImageAsset extends ImageData {
    constructor(data, width, height) {
        super(data, width, height);
    }
    static fromCanvas(canvas) {
        if(canvas instanceof HTMLCanvasElement) {
            var image = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height);
            return new ImageAsset(image.data, image.width, image.height);
        }
        else return null;
    }
    static fromFile(file) {

    }
    static fromImage(image) {
        if(image instanceof HTMLImageElement) {
            var canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            canvas.getContext("2d").drawImage(image, 0, 0);
            return this.fromCanvas(canvas);
        } else return null;
    }
    get canvas() {
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;
        canvas.getContext("2d").putImageData(this, 0, 0);
        return canvas;
    }
    get image() {
        var image = document.createElement("img");
        image.src = this.file;
        return image;
    }
    get file() {
        return this.canvas.toDataURL();
    }
    resize(width, height) {
        var canvas = document.createElement("canvas");
        var context = canvas.getContext("2d");
        canvas.width = width;
        canvas.height = height;
        context.drawImage(this.canvas, 0, 0, width, height);

        return ImageAsset.fromCanvas(canvas);
    }
    recolor(colors) {
        var compressor = new RgbQuant({colors: colors});
        compressor.sample(this);
        this.data.set(compressor.reduce(this));
    }

}

注意recolor 方法如何使用set 方法更改data 属性中的值,该属性由超类以只读方式保护Uint8ClampedArray。这是理想的行为。

但是,resize 方法返回我的对象​​的一个​​新实例,因为data 不能被覆盖(只读)或调整大小(类型化数组)。这是不利的。

如何使方法resize 将调用者的实例设置为具有新的datawidthheight 值,所有这些值都被超类保护为只读?

【问题讨论】:

标签: javascript arrays class typed-arrays


【解决方案1】:

您可以将dataheightwidth设置为this并在resize函数中使用

constructor(data, width, height) {
    super(data, width, height);

    this.data = data;
    this.width = width;
    this.height = height;
}


resize() {
    console.log(this.data, this.width, this.height);
}

希望有帮助

【讨论】:

  • 捕获类型错误:无法分配给对象“#”的只读属性“数据”
  • 也许你可以试试this.childData = data
  • 我可以重命名我自己的类中的属性,但是这样就失去了将我的类扩展到ImageData(继承原型方法)的好处。
  • 因此您可以创建函数来获取父类中的数据。例如:getData 返回 this.data
  • 很好奇您认为扩展ImageData 可以获得哪些好处。创建一个管理内部图像数据的类型不是更有意义吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 2021-12-15
  • 2011-11-10
  • 1970-01-01
  • 2021-10-01
相关资源
最近更新 更多