Cross-origin error getImageData

Harbinger: I know that several questions have been asked on this topic, but none of them seem to offer a direct JavaScript solution.

So, I ran into this error, where I am trying to get pixel data from the canvas using something like context.getImageData() , my exact code can be seen here or below:

 <canvas id="imageCanvas" width="600" height="800"></canvas> 
 // Load Image var canvas = document.getElementById('imageCanvas'); var image = new Image(); image.src = 'http://emoticons.pw/emoticons/emoticon-faces-002-medium.png'; image.onload = function() { width=image.width; height=image.height; var context = canvas.getContext('2d'); context.fillStyle="#024359"; // canvas background color context.fillRect(0, 0, width, height); context.drawImage(this,0,0); imageData = context.getImageData(0,0,width, height); // PROBLEM HERE context.putImageData(imageData, 0, 0); } 

In Chrome, the following errors occur:

It is not possible to get image data from the canvas because the canvas was corrupted by cross-origin data.

and then a security error. I do not want to make changes to the server or run chrome with unusual instructions. I feel that there is something in JavaScript that I can do.

Using local images is not a problem, but when I tried this, I got the same error!

I am trying to do this without a server, if I put this on my "default" godaddy web server, are all my problems resolved? I heard rumors that Dropbox can also simulate a server enough?

+8
source share
2 answers

You cannot use file:// if you use this (Chrome allows you to override this, but I will not recommend this).

For local testing, use a lightweight server like Mongoose, which allows you to use http://localhost as a domain to test your local pages. This way you will avoid problems with CORS.

If you need to place images in a different domain, you need to make sure that they support the use of different sources.

DropBox and ImgUrl (I recommend the latter only for images) support the use of CORS, but you need to request such use by adding the crossOrigin property to your image before setting up the source (or crossOrigin it in the HTML tag if you use it). ):

 var img = new Image; img.onload = myLoader; img.crossOrigin = ''; ///=anonymous img.src = 'http://imgur.com/....'; 

or in HTML:

 <img src="..." alt="" crossOrigin="anonymous" /> 
+10
source

Make sure you put img.setAttribute('crossOrigin', ''); before setting the source of your image object. exactly:

 var img = document.createElement("img"); //fix crossorigin here... img.setAttribute('crossOrigin', ''); //after that put your source img.src = imageSrcURL; document.body.appendChild(img); 
0
source

Source: https://habr.com/ru/post/957708/


All Articles