canvas 已被跨源数据污染

The canvas has been tainted by cross-origin data

问题

/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>

错误:

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

代码

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

调试解决方案

除了 headers,我认为您还需要将 crossorigin 属性添加到您的图片标签中。

示例图片标签:

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

如果您通过 javascript 执行此操作,这是您提供的 Mozilla link 中的代码示例:

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";

这是来自文档的重要段落(来源: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.

此外,此页面中的这段话可能会有帮助 (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.