尽管不经过 CORS 就能够在 Canvas 画布中使用图片,可是这会污染画布。一旦画布被污染,你就没法读取其数据。例如,你不能再使用画布的 toBlob(), toDataURL() 或 getImageData() 方法,调用它们会抛出安全错误。这种机制能够避免未经许可拉取远程网站信息而致使的用户隐私泄露。html
HTML 规范中图片有一个 crossorigin 属性,结合合适的 CORS 响应头,就能够实如今画布中使用跨域 <img>
元素的图像。前端
crossOrigin/CORS | 同域 | 跨域无 CORS | 跨域有 CORS |
---|---|---|---|
default | 支持 | 支持渲染,不支持 toDataURL |
支持渲染,不支持 toDataURL |
anonymous | N/A | 同上 | 支持渲染,支持 toDataURL |
use-credentials | N/A | 同上 | 支持渲染,不支持 toDataURL |
总结:Canvas 能够正常的渲染跨域图片,可是在跨域图片没有设置跨域响应头或没有设置 crossOrigin = 'anonymous'
的时候,使用 canvas.toDataURl
会抛出以下错误:git
Chromegithub
没有设置 crossOrigin
ajax
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at Image.img.onload...
跨域npm
Access to Image at 'http://localhost:3001/canvas.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
设置了 crossOrigin=use-credentials
json
Access to Image at 'http://localhost:3002/canvas.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access.
Safari/Firefoxcanvas
没有设置 crossOrigin
跨域
SecurityError: The operation is insecure.
浏览器
跨域
[Error] Origin http://192.168.3.99:3000 is not allowed by Access-Control-Allow-Origin. [Error] Failed to load resource: Origin http://192.168.3.99:3000 is not allowed by Access-Control-Allow-Origin. (canvas.jpg, line 0) [Error] Cross-origin image load denied by Cross-Origin Resource Sharing policy.
设置了 corssOrigin=use-credentials
[Error] Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true. [Error] Failed to load resource: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true. (canvas.jpg, line 0) [Error] Cross-origin image load denied by Cross-Origin Resource Sharing policy.
启动服务器
npm start
:启动服务器npm run start:corsdisable
:启动跨域图片服务器npm run start:corsable
:启动跨域-CORS图片服务器对于不支持 cossOrigin
的浏览器(IE 10及如下版本不支持,Android 4.3 及如下版本不支持)能够使用 XMLHttprequest
和 URL.createObjectURL()
来作兼容,参考测试示例 Ajax 解决 Canvas 图片跨域问题。
如今的前端开发通常都是将静态资源放置到 CDN 上,例如:阿里云或者腾讯云服务,而且会有一个专门的域名来访问这些资源。