Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-origin data in HTML5 canvas

I'm loading an image in js and draw it into a canvas. After drawing, i retrieve imageData from the canvas:

var img = new Image(); img.onload = function() {     canvas.drawImage(img, 0, 0);     originalImageData = canvas.getImageData(0,0,width, height)); //chrome fails } img.src = 'picture.jpeg'; 

This works perfectly both in Safari and Firefox, but fails in Chrome with the following message:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.

The javascript file and the image are located in the same directory, so i don't understand the behavior of chorme.

like image 726
Samuel Müller Avatar asked Apr 02 '12 06:04

Samuel Müller


People also ask

How do you allow cross-origin use of images and canvas?

HTML provides a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin.

What is web CORS in HTML5?

Advertisements. Cross-origin resource sharing (CORS) is a mechanism to allows the restricted resources from another domain in web browser. For suppose, if you click on HTML5- video player in html5 demo sections. it will ask camera permission.

How do you make a canvas not tainted?

By loading the canvas from cross origin domain, you are tainting the canvas. You can prevent this by setting crossorigin="anonymous" . However, CRAZILY enough, the order of the attribute on the img element does matter.


1 Answers

To enable CORS (Cross-Origin Resource Sharing) for your images pass the HTTP header with the image response:

Access-Control-Allow-Origin: * 

The origin is determined by domain and protocol (e.g. http and https are not the same) of the webpage and not the location of the script.

If you are running locally using file:// this is generally always seen as a cross domain issue; so its better to go via

http://localhost/ 
like image 79
Ben Adams Avatar answered Sep 24 '22 09:09

Ben Adams