Last active
August 29, 2015 14:08
-
-
Save ilguzin/c7527a3b5eff123d05d6 to your computer and use it in GitHub Desktop.
Average color of the picture. Stolen from http://jsfiddle.net/xLF38/ . Get data uri from image http://dataurl.net/#dataurlmaker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Setting the BODY's background to the average color in the following image: | |
<br/><br/> | |
<img id="i" src="data:image/jpeg;base64,/9j/7gAOQWRvYmUAZAAAAA........Q==" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getAverageRGB = (imgEl) -> | |
blockSize = 5 # only visit every 5 pixels | |
defaultRGB = | |
r: 0 # for non-supporting envs | |
g: 0 | |
b: 0 | |
canvas = document.createElement("canvas") | |
context = canvas.getContext and canvas.getContext("2d") | |
data = undefined | |
width = undefined | |
height = undefined | |
i = -4 | |
length = undefined | |
rgb = | |
r: 0 | |
g: 0 | |
b: 0 | |
count = 0 | |
return defaultRGB unless context | |
height = canvas.height = imgEl.naturalHeight or imgEl.offsetHeight or imgEl.height | |
width = canvas.width = imgEl.naturalWidth or imgEl.offsetWidth or imgEl.width | |
context.drawImage imgEl, 0, 0 | |
try | |
data = context.getImageData(0, 0, width, height) | |
catch e | |
alert "x" # security error, img on diff domain | |
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) | |
rgb | |
rgb = getAverageRGB(document.getElementById("i")) | |
document.body.style.backgroundColor = "rgb(" + rgb.r + "," + rgb.b + "," + rgb.g + ")" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment