0

I have the following Javascript code-

var img=new SimpleImage('image.png');

The dimension of the image.png file is 10x10. Now I need to access the pixel at coordinate (5,4) and get it's Red value. I've googled but cannot find a way to access the pixel using it's coordinate. How can I do this?

1 Answer 1

1

You have to load the image onto a canvas, use ctx.createImageData() to get the image data.

Excerpt copied from MDN

var img = new Image();
img.src = 'https://i.imgur.com/KM2bAUL.jpeg';
img.crossOrigin = "Anonymous";
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
img.onload = function() {
  ctx.drawImage(img, 0, 0, 300, 300);
  img.style.display = 'none';
};
var color = document.getElementById('color');
function pick(event) {
  var x = event.layerX;
  var y = event.layerY;
  var pixel = ctx.getImageData(x, y, 1, 1);
  var data = pixel.data;
  var rgba = 'rgba(' + data[0] + ', ' + data[1] +
             ', ' + data[2] + ', ' + (data[3] / 255) + ')';
  color.style.background =  rgba;
  color.textContent = rgba;
}
canvas.addEventListener('mousemove', pick);
<div id="color">I will change</div>
<canvas id="canvas" width="300px" height="400px"></canvas>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.