In javascript I am trying to extract the (R, G, B) value of a clicked pixel from the following image: http://map1.vis.earthdata.nasa.gov/wmts-webmerc/MODIS_Terra_Snow_Cover/default/2015-05-25/GoogleMapsCompatible_Level8/8/97/49.png
I am using the element and I set the crossOrigin="anonymous" attribute so that I can work with the data.
Here is my html and javascript code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<img src="http://map1.vis.earthdata.nasa.gov/wmts-webmerc/MODIS_Terra_Snow_Cover/default/2015-05-25/GoogleMapsCompatible_Level8/8/97/49.png"
crossOrigin="anonymous" width="256" height="256">
<pre id="output"></pre>
<script>
$(function() {
$('img').click(function(e) {
if(!this.canvas) {
this.canvas = $('<canvas/>').css({width:256 + 'px', height: 256 + 'px'})[0];
this.canvas.getContext('2d').drawImage(this, 0, 0, 256, 256);
}
var offX = (e.offsetX || e.clientX - $(e.target).offset().left);
var offY = (e.offsetY || e.clientY - $(e.target).offset().top);
console.log(offX + ' ' + offY);
var pixelData = this.canvas.getContext('2d').getImageData(offX, offY, 1, 1).data;
$('#output').html('offX:' + offX + ' offY:' + offY +
'<br>R: ' + pixelData[0] +
'<br>G: ' + pixelData[1] +
'<br>B: ' + pixelData[2] +
'<br>A: ' + pixelData[3]);
});
});
</script>
</body>
</html>
I've also put my code on jsfiddle: http://jsfiddle.net/32beaobL/
The problem is that this code gets the correct RGB value of the clicked pixel only until around row 149 of the image. for rows 149 and greater, it returns (0,0,0) for any pixel even though the pixel has a non-white color.
Any idea what's going on?
You resized the canvas with CSS, so the canvas was never over 150px tall (default canvas size is 300 x 150).
Here is your example fixed: http://jsfiddle.net/32beaobL/1/
This is the code that changed
if(!this.canvas) {
this.canvas = document.createElement('canvas');
this.canvas.width = 256;
this.canvas.height = 256;
this.canvas.getContext('2d').drawImage(this, 0, 0, 256, 256);
}