Skip to content

Instantly share code, notes, and snippets.

@danasf
Created August 23, 2014 22:31
Show Gist options
  • Save danasf/15a52a5b4d19c386e600 to your computer and use it in GitHub Desktop.
Save danasf/15a52a5b4d19c386e600 to your computer and use it in GitHub Desktop.
RGBs
<html>
<head>
<title>Get some RGBA data from canvas!</title>
</head>
<body>
<h1>Get RGBs from canvas</h1>
<canvas id="acanvas" width="300" height="300"></canvas>
</body>
<script type="text/javascript">
;(function() {
var getColorAtPos = function (x,y) {
var pos = ((y * can.width) + x)*4;
var imgData = con.getImageData(0,0,can.height,can.width).data;
if(can.width >= x && can.height >= y) {
return { r:imgData[pos], g:imgData[pos+1], b:imgData[pos+2], a:imgData[pos+3] };
} else {
return {r:0, g:0,b:0,a:0 };
}
};
var can = document.getElementById('acanvas');
var con = can.getContext('2d');
con.rect(0,0,can.height,can.width);
con.fillStyle = "#00ff00"
con.fill()
con.fillStyle = "#ff0000"
con.fillRect(0,0,100,100);
var imageData = con.getImageData(0,0,can.height,can.width);
can.addEventListener("click",function(e) {
console.log("Mouse event",e.clientX,e.clientY);
console.log(getColorAtPos(e.clientX,e.clientY));
}, false);
})();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment