I'm trying to read image data through the canvas tag and every time I try to retrieve and display that data it all comes up 0's. Even if I limit the data grab to 1 pixel it comes up "0, 0, 0, 0". The odd thing is that I can use fillRect and retrieve that data, but when drawing an image it comes up zeros. I'll be using this script to compare pixels to find out if the pattern is repeatable, but first I need to make sure I can read that data in the first place.
Below is my code. I'm sort of old fashion and use a text editor and browser to test with. As a result, I don't have this up on any WYSIWYG editors that some people use. You'll just have to use an image and change the source to get it to work locally. Though I could set it up elsewhere if requested.
I hope I can get some insight as to why this isn't working.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body { background-color:#dedddd }
canvas { background-color:white; padding:20px }
#colorInfo { width:300px; background-color:white; padding:20px }
</style>
</head>
<body>
<canvas id="iLikeCookies" width="300" height="300">Your browser kinda sucks. Can't even draw a canvas. For shame.</canvas>
<div id="header"></div>
<div id="colorInfo"></div>
<script>
var canvas = document.getElementById('iLikeCookies');
var ctx = canvas.getContext('2d');
var img = new Image();
pixelData = '';
// function to read all pixels and build into string of RGBa values.
var read = function() {
// loop through each row
for(var y = 0; y < canvas.height; y++) {
// loop through each column
for(var x = 0; x < canvas.width; x++) {
// grabbing individual pixel data
var red = pixels[((canvas.width * y) + x) * 4];
var green = pixels[((canvas.width * y) + x) * 4 + 1];
var blue = pixels[((canvas.width * y) + x) * 4 + 2];
var alpha = pixels[((canvas.width * y) + x) * 4 + 3];
// adding current pixel data to string
pixelData += "RGBa(" + red + ", " + green + ", " + blue + ", " + alpha + ") <br/>";
}
}
};
img.onload = function() {
ctx.drawImage(img, 0, 0, 300, 300);
};
// ctx.fillStyle = "rgb(123,40,170)"
// ctx.fillRect(0,0,300,300)
img.src = 'pattern2.jpg';
imgData = ctx.getImageData(0, 0, canvas.width-299, canvas.height-299);
pixels = imgData.data
read();
console.log(img.width + ", " + img.height);
document.getElementById("header").innerHTML = "Here are the " + canvas.height*canvas.width + " pixels found in the image.<br/>";
document.getElementById("colorInfo").innerHTML = pixelData;
console.log(pixelData);
</script>
</body>
</html>