儘管不經過 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 上,例如:阿里雲或者騰訊雲服務,而且會有一個專門的域名來訪問這些資源。