0

I am loading a black and white image from my computer on a web page and then drawing the image in a canvas. Then I want to retrieve the color of the first pixel. Here's the JavaScript function I am using:

function loadImage(){
    var c=document.getElementById("canvas");
    var ctx=c.getContext("2d");
    var img=document.getElementById("first");
    ctx.drawImage(img,0,0);
    var z1=ctx.getImageData(0, 0, 1, 1).data[0];
    document.getElementById("1").value=z1;
};

I am getting the following error:

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

Any ideas how I can achieve my requirement? This is part of a project I'm working on where I want to create a genetic algorithm that draws a given picture. An important part of this project is comparing the pixels from the initial image (loaded in a canvas) to a canvas populated by pseudo-random pixels. I then introduce small variance to the pixels to evolve it towards the initial image.

If I draw the canvas manually (using fillRect) I can retrieve the pixel data using 'getImageData'. However, when I draw the canvas using an image (drawImage), I get the above mentioned error.

Please help.

Edit: I've looked at: How to fix getImageData() error The canvas has been tainted by cross-origin data?

But this is not the case. I am loading the image from my own computer. I simply have the .html, .js and .png files in the same folder and run the .html file.

Community
  • 1
  • 1
letsplay14me
  • 59
  • 1
  • 7
  • I was about to say the same. The answer there explains the issue...I'm guessing you're loading your image from another url or source? – Ageonix Feb 28 '16 at 13:54
  • I am loading the image from my own computer, like this: I found that answer too, but I couldn't understand how to fix this. – letsplay14me Feb 28 '16 at 14:03
  • From what I was able to understand, I need to set the "crossOrigin" attribute of the to "Anonymous" and "set the following header on the server": Access-Control-Allow-Origin "*". I can't add that attribute to my tag, because I get the following error: "Image from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access.". And I don't know how to set the header on the server. The server is my own PC. I run a HTML file. – letsplay14me Feb 28 '16 at 14:11

1 Answers1

0

Ok, I've installed WAMP, put everything in the "www" folder and ran it from there. Worked.

letsplay14me
  • 59
  • 1
  • 7
  • Since your question is a duplicate of previously asked questions, you might want to delete your answer and your question. ;-) – markE Feb 28 '16 at 18:17