儘管不通過 CORS 就可以在 Canvas 畫布中使用圖片,但是這會污染畫布。一旦畫布被污染,你就無法讀取其數據。例如,你不能再使用畫布的 toBlob(), toDataURL() 或 getImageData() 方法,調用它們會拋出安全錯誤。這種機制可以避免未經許可拉取遠程網站信息而導致的用戶隱私泄露。
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
會拋出如下錯誤:
-
Chrome
沒有設置
crossOrigin
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at Image.img.onload...
跨域
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
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/Firefox
沒有設置
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圖片服務器
-
- 訪問 http://localhost:3000
其他問題
- cossOrigin 存在兼容性問題
對於不支持
cossOrigin
的瀏覽器(IE 10及以下版本不支持,Android 4.3 及以下版本不支持)可以使用XMLHttprequest
和URL.createObjectURL()
來做兼容,參考測試示例 Ajax 解決 Canvas 圖片跨域問題。 - 爲什麼不使用同域圖片?
現在的前端開發一般都是將靜態資源放置到 CDN 上,例如:阿里雲或者騰訊雲服務,並且會有一個專門的域名來訪問這些資源。