Yafim Simanovsky Yafim Simanovsky - 1 month ago 15
AngularJS Question

Canvas & Color-Thief image index size

I'm using

to analyze the colors of images. I'm using a canvas and
getImageData
, I'm getting the following error message in the console:

Error: Index or size is negative or greater than the allowed amount
CanvasImage.prototype.getImageData@http://localhost:3000/js/color-thief.js:51:12
ColorThief.prototype.getPalette@http://localhost:3000/js/color-thief.js:109:22
ColorThief.prototype.getColor@http://localhost:3000/js/color-thief.js:75:25
colorController/this.getColors@http://localhost:3000/js/ang.js:20:22


I'm not sure if this is a canvas issue coming from image pixel size or if it's some bug in another library (I'm also using AngularJS) but I'm stuck and not sure what I can do.

I think there is an issue with pixel count being 0, when I add the
console.log
line to the following code inside color-thief.js then I get "0 0" for some images.

Crucial point --> the
image.width
and
image.height
show 0 only for SOME images, while the rest it shows ratios that make sense like 1280 922 or 2000 1333.

var CanvasImage = function (image) {
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');

document.body.appendChild(this.canvas);

this.width = this.canvas.width = image.width;
this.height = this.canvas.height = image.height;

console.log(image.width, image.height);

this.context.drawImage(image, 0, 0, this.width, this.height);
};


Any idea why this can happen?

Answer

The answer was to add the image.addEventListener("load", function() { ... } to the code to load the image correctly.

Comments