2016-09-25 72 views
2

我使用color-thief來分析圖像的顏色。我使用的是帆布和getImageData,我收到以下錯誤消息在控制檯:Canvas&Color-Thief image index size

Error: Index or size is negative or greater than the allowed amount 
[email protected]://localhost:3000/js/color-thief.js:51:12 
[email protected]://localhost:3000/js/color-thief.js:109:22 
[email protected]://localhost:3000/js/color-thief.js:75:25 
colorController/[email protected]://localhost:3000/js/ang.js:20:22 

我不知道這是否是從圖像像素大小來畫布問題,或者如果它在一些bug另一個庫(我也使用AngularJS),但我卡住了,不知道我能做什麼。

我認爲有一個像素數爲0的問題,當我將console.log行添加到color-thief.js中的以下代碼中時,那麼對於某些圖像我會得到「0 0」。

要害 - >的image.widthimage.height顯示爲0只爲某些圖像,而其餘它顯示比例,使像1280 922或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); 
}; 

任何想法,感覺,爲什麼會發生這種情況?

+0

我試圖找出爲什麼有些圖像顯示INDEX錯誤,而其他圖像不顯示。 到目前爲止,似乎沒有jpg或png或文件大小或分辨率維度之間的分離......所有案例都有圖像工作和圖像不工作。 另一個奇怪的事實是:在清理本地主機緩存並加載頁面時,100%的圖像會發生錯誤。如果刷新,該網站只顯示一些錯誤。這是隨機的,意思是在刷新時可能會隨機更改什麼詞,什麼不是INDEX錯誤。 任何幫助,將不勝感激。 –

+3

你在哪裏將圖像傳入函數?你在等待onload事件嗎?未加載的圖像將具有零大小。 – rlemon

回答

0

答案是將image.addEventListener("load", function() { ... }添加到代碼以正確加載圖像。