Hello Goodbye
Hello Goodbye

Reputation: 134

Why doesn't my code to get pixel data from an image work?

I made this code to cycle through every pixel in an image and output its RGBA value to the console. Why doesn't it work as intended? I seem to be getting all [0,0,0,0]s for PixelData. I tried several pieces of code from stackoverflow.com but they didn't help. My ultimate goal is to compare these colors to a list of other colors and pick the closest one for each pixel, but I should be able to do that alone once I get this part answered.

<!doctype html>
<html>
<head>
<img id="myImage" src="img.png" width="64px" height="64px"></img>
<script>
var img = document.getElementById('myImage');
var mycanvas = document.createElement('canvas');
mycanvas.width = img.width;
mycanvas.height = img.height;
var context = mycanvas.getContext('2d');
context.drawImage(img, 0, 0, img.width, img.height);
for(var x=1;x<=16;x++){
for(var y=1;y<=16;y++){
var pixelData = context.getImageData(x, y, 1, 1).data;
console.log("x="+x.toString()+" y="+y.toString()+" pD="+pixelData.toString()+" ");
}}
</script></head>
<body></body>
</html>

Upvotes: 0

Views: 131

Answers (1)

kshetline
kshetline

Reputation: 13734

You might not be giving your image enough time to load and render. Try using img.onload like this:

var img = document.getElementById('myImage');

img.onload = function() {
  var mycanvas = document.createElement('canvas');
  mycanvas.width = img.width;
  mycanvas.height = img.height;
  var context = mycanvas.getContext('2d');
  context.drawImage(img, 0, 0, img.width, img.height);
  for(var x=1;x<=16;x++){
    for(var y=1;y<=16;y++){
      var pixelData = context.getImageData(x, y, 1, 1).data;
      console.log("x="+x.toString()+" y="+y.toString()+" pD="+pixelData.toString()+" ");
    }
  }
}

Oh, and one more thing... Move your <img...> tag out of the head section of your HTML and into the body. I'm not sure an image will even load if it's in the head section. If you do this either your script will have to follow the image, or you'll have to wrap your script in a function that's called when your document finishes loading, e.g. <body onload="init()">.

Update:

I found this post about putting an img in your head section. It sounds like you're likely to get away with it, but you shouldn't count on it: Will an html image tag execute in the head tag

Upvotes: 2

Related Questions