I have this error
Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.
It comes only, if i changed the url to a lowerpage like example.com/test when i go back than to the frontpage or something
Or it comes also if you open DevTools on Chrome and simulate a phone or something, reload than and i get this error.
After another reload it works. I dont know why... Everytime the first reload when you entered another page, than it doesnt work. But the 2nd reload than works.
Its a code to pick average color of an image
var blockSize = 5, // only visit every 5 pixels
defaultRGB = {r:-62,g:-62,b:-62}, // for non-supporting envs
canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgb = {r:-62,g:-62,b:-62},
count = 0;
if (!context) {
return defaultRGB;
}
var imgElReady = false;
var imgEl = new Image();
imgEl.onload = function(){
imgElReady = true;
}
imgEl.src = imageurl;
height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
context.drawImage(imgEl, 0, 0);
try {
data = context.getImageData(0, 0, width, height);
console.log(data)
console.log('test1')
} catch(e) {
console.log('test2')
return defaultRGB;
}
length = data.data.length;
while ( (i += blockSize * 4) < length ) {
++count;
rgb.r += data.data[i];
rgb.g += data.data[i+1];
rgb.b += data.data[i+2];
}
// ~~ used to floor values
rgb.r = ~~(rgb.r/count);
rgb.g = ~~(rgb.g/count);
rgb.b = ~~(rgb.b/count);
return rgb;
On this example, every load when you change the size from normal to simulate a phone or something, the first load jump into console.log test2. And if you reload than again on the same size and page it works
I also checked imgEl after the imgEl.src, an all loads it looks the same and there are images
I know there some other peoples with that bug, but no one has the same problem as my example
The code works only if i load the exact page 2nd time or more. Never on the first load