仅在预加载图像时,画布才会出现CORS问题 [英] CORS issue with canvas only when image is preloaded

查看:109
本文介绍了仅在预加载图像时,画布才会出现CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题仅在加载的图像被预加载到其他地方时出现.例如,当我在某处使用带有src属性的<img>-标签.

My issue only arises when the loaded image was preloaded somewhere else. For example, when I somewhere use a <img>-tag with the src attribute.

看看这段代码:

 <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;" ></canvas>
 
 <img src="https://local-spaces.fra1.digitaloceanspaces.com/test.jpg" width="50"/>
 
 <button onclick="show()">Load Canvas Picture</button>
 
 <script>
function show() {
  	const c = document.getElementById("myCanvas");
    const ctx = c.getContext("2d");

    const img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');


    img.onload = function(){
      ctx.drawImage(img,0,0, 300, 150);
    };
		
    img.src = "https://local-spaces.fra1.digitaloceanspaces.com/test.jpg"
   
}
</script>

注意:如果您在画布上正确看到图像,请缓存并重新加载浏览器以查看错误.

如果您单击该按钮并打开控制台,您将看到出现CORS错误:

If you are clicking on the button and open your console, you will see that you are getting a CORS-error:

在以下位置访问图像 ' https://local-spaces.fra1.digitaloceanspaces.com/test.jpg

Access to image at 'https://local-spaces.fra1.digitaloceanspaces.com/test.jpg' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

现在,让我们来看下一个示例,它可以在不预加载图像的情况下运行: https://jsfiddle.net/akzxp9vs/

Now let's take the next example to see that it is working without preloading the image: https://jsfiddle.net/akzxp9vs/

注意:要使此示例正常工作,删除缓存+强制重新加载浏览器非常重要.

只有这样,您才能看到正确的标头响应正在回馈.

Only then you see that the correct header response is giving back.

有什么想法我能做什么?

Any ideas what I can do?

该图像位于S3数字海洋云中,称为空间.图片本身设置为公开,CORS设置设置为:

The image is on the S3 Cloud of Digital Ocean, called Spaces. The image itself is set to public and the CORS setting are set to:

推荐答案

在发出HTTP请求时(即包含Origin标头等),浏览器需要知道检查CORS权限.

The browser needs to know to check for CORS permissions when the HTTP request is made (i.e. to include an Origin header etc).

创建新的Image对象时,该对象将使用<img>元素中的缓存数据.

When you create a new Image object, it uses the cached data from the <img> element.

向现有属性添加 crossorigin 属性<img>元素或完全删除该<img>元素.

Add a crossorigin attribute to the existing <img> element or remove that <img> element entirely.

这篇关于仅在预加载图像时,画布才会出现CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆