我创建了自己的类,扩展了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
将调用者的实例设置为具有新的data
,width
和height
值,所有这些值都被保护为已读 - 只有超类?
答案 0 :(得分:0)
您可以将data
,height
,width
设置为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);
}
希望这个帮助