首頁  >  文章  >  web前端  >  Canvas圖片跨域會遇到的問題及解決方法總結

Canvas圖片跨域會遇到的問題及解決方法總結

不言
不言原創
2018-09-17 16:04:016803瀏覽

這篇文章帶給大家的內容是關於Canvas圖片跨域會遇到的問題及解決方法總結,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

儘管不通過 CORS 就可以在 Canvas 畫布中使用圖片,但這會污染畫布。一旦畫布被污染,你就無法讀取其資料。例如,你不能再使用畫布的 toBlob(), toDataURL() 或 getImageData() 方法,呼叫它們會拋出安全性錯誤。這種機制可以避免未經許可拉取遠端網站資訊而導致的用戶隱私外洩。

HTML 規範中圖片有一個 crossorigin 屬性,結合合適的 CORS 回應頭,就可以實現在畫布中使用跨域 元素的圖像。

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.

測試範例

1、啟動伺服器

npm start:啟動伺服器

npm run start:corsdisable:啟動跨網域圖片伺服器

npm run start:corsable:啟動跨網域-CORS圖片伺服器

2、造訪http://localhost:3000

其他問題

##1、 cossOrigin 有相容性問題

對於不支援cossOrigin 的瀏覽器(IE 10及以下版本不支持,Android 4.3 及以下版本不支援)可以使用XMLHttprequest 和URL.createObjectURL() 來做相容,參考測試範例Ajax 解決Canvas 圖片跨域問題。

2、為什麼不使用同域圖片?

現在的前端開發一般都是將靜態資源放置到 CDN 上,例如:阿里雲或騰訊雲服務,並且會有一個專門的網域來存取這些資源。

#

以上是Canvas圖片跨域會遇到的問題及解決方法總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn