Created
August 5, 2017 01:09
-
-
Save tommyready/52b99611271b9c6eaf7d545428431d96 to your computer and use it in GitHub Desktop.
Use pure JavaScript to get the color of a pixel on click
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
<script type="text/javascript" language="javascript"> | |
var img = document.getElementById("myImage"); | |
img.addEventListener("click", function(event) { | |
var canvas = document.createElement('canvas'); | |
canvas.width = img.width; | |
canvas.height = img.height; | |
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height); | |
var p = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data; | |
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6); | |
console.log( hex ); | |
}); | |
function rgbToHex(r, g, b) { | |
if (r > 255 || g > 255 || b > 255) | |
throw "Invalid color component"; | |
return ((r << 16) | (g << 8) | b).toString(16); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment