我应该在哪里设置 CORS 设置,这样我的画布才不会被污染? [英] What do I set CORS settings to and where so that my canvas doesn't get tainted?
问题描述
我有一个大画布,上面有来自我的 S3 存储桶的图标和图片.当我尝试上传它时(运行 toDataUrl
)Chrome 抱怨说
I have a big canvas with icons and pictures that all come from my S3 bucket. When I'm trying to upload it (which runs toDataUrl
) Chrome complains that
无法在HTMLCanvasElement"上执行toDataURL":受污染的画布可能无法导出.
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
我之前遇到过这个错误,但我当时的解决方案是在本地托管所有图像.但是,这一次是不可能的,所以我需要正面解决这个问题.
I've encountered this error before, but my solution that time was to host all the images locally. This is not possible this time, however, so I will need to tackle this issue head on.
谷歌搜索这个问题带来了很多关于 CORS 的东西,我不明白.
Googling this issue brings up a lot of stuff about CORS, which I don't understand.
我在我的 S3 存储桶中尝试了以下设置:
I've tried the following settings in my S3 bucket:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedOrigin>Anonymous</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
但是,这不起作用.
我的直觉告诉我,我也必须更改服务器中的某些内容,否则这个安全要求的目的是什么?
My intuition tells me I have to change something in the server as well, otherwise what is the purpose of this security requirement?
那么我要改变什么,在哪里,这样我的画布就不会再被污染了?
So what do I change, and where, so that my canvas won't be tainted anymore?
推荐答案
你的 CORS 配置应该是好的,最少需要是
Your CORS configuration should be good, the minimal needed being
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
但是,您需要设置 <img>
的 crossOrigin
属性 到 "anonymous"
.
What you need however, is to set your <img>
's crossOrigin
attribute to "anonymous"
.
另外,检查 s3 上的图像是否已公开(应该有一个被授权者 Everyone
设置为 Open/Download
),并且您使用了可用的链接在图像文件的 Properties
选项卡中(类似于 https://s3.yourRegion.amazonaws.com/userName/Folder/file.png
).
Also, check that the image on s3 has been made Public (there should be a grantee Everyone
set to Open/Download
), and that you use the link available in the Properties
tab of your image file (something like https://s3.yourRegion.amazonaws.com/userName/Folder/file.png
).
最后,您必须在更改存储桶的 CORS 设置后清除浏览器的缓存,否则浏览器不会向服务器发出新请求,并且会使用它缓存的不安全版本.
And finally, you have to clear the browser's cache after you changed your bucket's CORS setting, otherwise the browser won't make a new request to the server and it will use the unsafe version it has cached.
这篇关于我应该在哪里设置 CORS 设置,这样我的画布才不会被污染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!