Last active
May 24, 2018 17:04
-
-
Save TrevorJTClarke/bb1933004a77b4ac476bf1b29925ff4b to your computer and use it in GitHub Desktop.
Get Color From Image
This file contains hidden or 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
function rgbToHex(r, g, b) { | |
if (r > 255 || g > 255 || b > 255) throw 'Invalid color component' | |
return ((r << 16) | (g << 8) | b).toString(16) | |
} | |
const generateColor = src => { | |
return new Promise((res, rej) => { | |
let c = document.createElement('canvas') | |
if (c.getContext) { | |
c = c.getContext('2d') | |
const i = new Image() | |
i.crossOrigin = 'Anonymous' | |
i.onload = () => { | |
c.drawImage(i, 0, 0) | |
const p = c.getImageData(20, 20, 50, 50).data | |
const hex = '#' + ('000000' + rgbToHex(p[0], p[1], p[2])).slice(-6) | |
res(hex) | |
} | |
i.onerror = () => { | |
rej('#003366') | |
} | |
i.src = src | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment