简体   繁体   中英

The canvas has been tainted by cross-origin data

Problem

/etc/apache2/apache2.conf

 <Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
     <IfModule mod_setenvif.c>
<IfModule mod_headers.c>
    <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
        SetEnvIf Origin ":" IS_CORS
        Header set Access-Control-Allow-Origin "*" env=IS_CORS
    </FilesMatch>
</IfModule>
</IfModule>
  </Directory>
  • start the apache again .

Bug:

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

Code

        var image = ctx.getImageData(0, 0, canvas.width, canvas.height),//debugger breakpoint stop here.
        imageData = image.data;

Debug solution

  • i have googled and find that no browser will allow cross origin images.
  • i don"t need to save images of cross origin .
  • change in .htaccess file.
  • how to debug the issue.

Along with the headers, I think you need to add the crossorigin attribute to your image tag.

Example image tag:

<img src="www.domain.com/image.jpg" crossorigin="anonymous" />

If you are doing this via javascript, here is the code example in the Mozilla link you provided:

var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here

// Notice that they set the cross origin attribute here
img.crossOrigin = "Anonymous";

Here is elevant passage from the docs (Source: https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image ):

The HTML specification introduces a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the element loaded from foreign origins to be used in canvas as if they were being loaded from the current origin.

And also this passage may be helpful from this page ( https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes ):

By default (that is, when the attribute is not specified), CORS is not used at all. The "anonymous" keyword means that there will be no exchange of user credentials via cookies, client-side SSL certificates or HTTP authentication as described in the Terminology section of the CORS specification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM