HTML 規范文檔為 images 引入了 crossorigin 屬性, 通過設置適當的頭信息 CORS , 可以從其他站點加載 img 圖片, 并用在 canvas 中,就像從當前站點(current origin)直接下載的一樣.
crossorigin 屬性的使用細節, 請參考CORS settings attributes.
什么是 “被污染的(tainted)” canvas?
盡管沒有CORS授權也可以在 canvas 中使用圖像, 但這樣做就會污染(taints)畫布。 只要 canvas 被污染, 就不能再從畫布中提取數據, 也就是說不能再調用 toBlob(), toDataURL() 和 getImageData() 等方法, 否則會拋出安全錯誤(security error).
這實際上是為了保護用戶的個人信息,避免未經許可就從遠程web站點加載用戶的圖像信息,造成隱私泄漏。
(譯者注: 如果用戶登陸過QQ等社交網站, 假若不做保護 ,則可能打開某個網站后,該網站利用 canvas 將用戶的圖片信息獲取,上傳,進而引發泄露.)
示例: 從其他站點保存圖片
首先, 圖片服務器必須設置相應的 Access-Control-Allow-Origin
響應頭。添加 img 元素的 crossOrigin 屬性來請求頭。比如Apache服務器,可以拷貝HTML5 Boilerplate Apache server configs 中的配置信息, 來進行回應:
<IfModule mod_setenvif.c> <IfModule mod_headers.c> <FilesMatch "/.(cur|gif|ico|jpe?g|png|svgz?|webp)$"> SetEnvIf Origin ":" IS_CORS Header set Access-Control-Allow-Origin "*" env=IS_CORS </FilesMatch> </IfModule></IfModule>
這些設置生效之后, 就可以像本站的資源一樣, 保存其他站點的圖片到 DOM存儲 之中(或者其他地方)。
var img = new Image, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), src = "http://example.com/image"; // 具體的圖片地址img.crossOrigin = "Anonymous";img.onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage( img, 0, 0 ); localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );}img.src = src;// 確保緩存的圖片也觸發 load 事件if ( img.complete || img.complete === undefined ) { img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; img.src = src;}
瀏覽器兼容性
Desktop
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 13 | 8 | No support | No support | ? |
Mobile
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | ? | ? | ? | ? | ? |
另請參見
Chrome:在WebGL中使用跨域圖片
HTML規范-crossorigin屬性
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答