【问题标题】:new Image not working with crossOrigin "Anonymous"新图像不适用于 crossOrigin \"Anonymous\"
【发布时间】:2022-11-04 14:56:12
【问题描述】:

所以我试图将这些网址之一加载到new Image,但它们似乎都没有加载。我有一个 image.onload 功能,但它没有去那里。但是,如果我删除 image.crossOrigin,它就可以工作。但问题是如果我删除了 crossOrigin。我将在 onload 中的函数中收到画布污染错误。

这是一个示例 jsfiddle:https://jsfiddle.net/p3b7y8ns/2/

const corrupt_svg = 'https://files.23point5.com/file?path=/artist-library/5119c74c- 
c072-4913-9dca-89b616306f1c.svg'
const fixed_svg = 'https://dev-files.23point5.com/file?path=/artist-library/aaa4f68f- 
02f1-49a4-bf21-fc3c54a28d23.svg'

const normal_image ='https://dev-files.23point5.com/file?path=/artist- 
library/865a8f92-5c5b-466e-96e5-04a668bc3294.jpeg'
console.log('running')
const image = new Image()

image.crossOrigin = 'Anonymous'
image.onload = () => {
   console.log('loaded')
   console.log("image", image);
   const canvas = document.createElement("canvas");
   canvas.width = image.naturalWidth;
   canvas.height = image.naturalHeight;
   const ctx = canvas.getContext("2d");
   ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
   console.log("canvas", canvas);
   canvas.toDataURL();
  }

image.src = normal_image

【问题讨论】:

    标签: javascript image svg canvas cors


    【解决方案1】:

    出于安全原因,浏览器不允许加载来自未知来源的图像。 Here is a good article defining the behaviour.

    为了能够在没有污染画布的情况下加载,您应该检查您的服务器 CORS 配置并查看您当前的工作域是否被允许作为 Origin

    本地主机也必须启用,默认情况下不启用。 例如。要设置为服务器上的标头的配置选项:访问控制允许来源:本地主机

    请注意,这种方式只能指定一个原点。如果服务器支持来自多个来源的客户端,它必须返回发出请求的特定客户端的来源。 Link

    另请注意,对于大多数服务器,都有很好的库可以轻松启用和处理这些类型的 CORS 选项,您应该查看它或要求您的后端开发人员添加必要的域。

    如果 CORS 设置正确,那么您可以安全地删除匿名设置。 Anonymus 基本上尝试在没有任何凭据的情况下调用服务器资源。如果发生这种情况,则由服务器决定是否为请求提供服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2017-10-19
      • 1970-01-01
      • 2018-09-05
      • 2021-09-17
      • 2018-03-16
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多