getImageData() 数组在 angular 5 中返回全 0

getImageData() array is returning all 0s in angular 5

我试图在 canvas 内渲染图像后获取图像的 rgb 值。但是,我在 return 中得到的全是 0。我在渲染图像后尝试使用 getImageData() 不确定为什么我在 return 中得到 0。

我的代码:

fileSelected: File;
preview: any;
context: CanvasRenderingContext2D;
hue: any;
myImageData:any

onFileSelect(e: any) {
    let canvas = this.mycanvas.nativeElement;
    let context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height)
    let imgData;
    this.fileSelected = e.target.files[0];
    let reader = new FileReader()
    reader.onload = (e: any) => {
        var image = new Image();
        image.onload = function () {
            image.width = canvas.width;
            image.height = canvas.height;
            context.drawImage(image, 0, 0, canvas.width, canvas.height)
         };
        image.src = e.target.result

    }
    reader.readAsDataURL(this.fileSelected);
    this.myImageData = context.getImageData(0, 0, 100, 100);

    this.hue = this.calculateHue(this.fileSelected, this.myImageData);
}

calculateHue(file, myImageData) {

     console.log("rgb====", myImageData.data)
    return null
}

我浏览了这些链接, getImageData() returning all 0's, getImageData always returning 0

但是 none 个答案解决了它。我做错了什么?

您在加载图像后立即写入 canvas,但是您在选择文件后立即尝试从 canvas 读取,移动:

this.myImageData = context.getImageData(0, 0, 100, 100);
this.hue = this.calculateHue(this.fileSelected, this.myImageData);

进入 image.onload 并在 context.drawImage(image, 0, 0, canvas.width, canvas.height) 调用之后,因此您确定有图像数据可以读取。

它应该看起来像这样:

onFileSelect(e: any) {
    let canvas = this.mycanvas.nativeElement;
    let context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height)
    let imgData;
    this.fileSelected = e.target.files[0];
    let reader = new FileReader();
    let self = this;

    reader.onload = (e: any) => {
        var image = new Image();
        image.onload = () => {
            image.width = canvas.width;
            image.height = canvas.height;
            context.drawImage(image, 0, 0, canvas.width, canvas.height)
            // Move it here
            self.myImageData = context.getImageData(0, 0, 100, 100);
            self.hue = this.calculateHue(self.fileSelected, self.myImageData);
         };

        image.src = e.target.result
    }
    reader.readAsDataURL(this.fileSelected);
}