调整只读类型数组的大小

时间:2018-04-12 06:37:46

标签: javascript arrays class typed-arrays

我创建了自己的类,扩展了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如何使用方法data更改Uint8ClampedArray属性中的值,该属性set被超类保护为只读。这是理想的行为。

但是,方法resize返回我的对象​​的新实例,因为data不能被覆盖(只读)或调整大小(typed-array)。这是不利的。

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

1 个答案:

答案 0 :(得分:0)

您可以将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);
}

希望这个帮助

相关问题