Reputation: 1790
I have a css style which in its background it has an image for example it is like this code
.test {
background-image: url("paper.gif");
background-color: #cccccc;
}
well I also have a javascript code which is used to get average color of an image,
function getAverageRGB(imgEl) {
var blockSize = 5, // only visit every 5 pixels
defaultRGB = {r:0,g:0,b:0}, // for non-supporting envs
canvas = document.createElement('canvas'),
context = canvas.getContext && canvas.getContext('2d'),
data, width, height,
i = -4,
length,
rgb = {r:0,g:0,b:0},
count = 0;
if (!context) {
return defaultRGB;
}
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);
} catch(e) {
/* security error, img on diff domain */alert('x');
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;
}
As the above code shows I have to pass an image element into the function, but In fact I do not have any tag and I only have a div which its css has a background image, How can I read the images data? thansk
Upvotes: 2
Views: 2337
Reputation: 657
You can create a Image element using yours div background-img as source.
img = new Image();
img.src = divTest.style.backgroundImage;
Upvotes: 5
Reputation: 2008
You need to modify the function getAverageRGB to draw the image from the url in the background of the div, then you just pass your div and the modified function will draw the image onto the canvas - see docs below.
This question solves that problem
Drawing an image from a data URL to a canvas
Upvotes: 3