Skip to content

Instantly share code, notes, and snippets.

@tommyready
Created August 5, 2017 01:09
Show Gist options
  • Save tommyready/52b99611271b9c6eaf7d545428431d96 to your computer and use it in GitHub Desktop.
Save tommyready/52b99611271b9c6eaf7d545428431d96 to your computer and use it in GitHub Desktop.
Use pure JavaScript to get the color of a pixel on click
<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