詳解canvas繪圖時(shí)遇到的跨域問題

當(dāng)在canvas中繪制一張外鏈圖片時(shí),我們會遇到一個(gè)跨域問題。
示例如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>crossorigin</title> </head> <body> <canvas width="600" height="300" id="canvas"></canvas> <img id="image" alt=""> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.onload = function() { ctx.drawImage(image, 0, 0); document.getElementById('image').src = canvas.toDataURL('image/png'); }; image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg'; </script> </body>
當(dāng)在瀏覽器中打開這個(gè)頁面時(shí),你會發(fā)現(xiàn)這個(gè)問題:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
這是受限于 CORS 策略,會存在跨域問題,雖然可以使用圖像,但是繪制到畫布上會污染畫布,一旦一個(gè)畫布被污染,就無法提取畫布的數(shù)據(jù),比如無法使用使用畫布toBlob(),toDataURL(),或getImageData()方法;當(dāng)使用這些方法的時(shí)候 會拋出上面的安全錯誤
這是一個(gè)苦惱的問題,但幸運(yùn)的是img新增了crossorigin屬性,這個(gè)屬性決定了圖片獲取過程中是否開啟CORS功能:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>crossorigin</title> </head> <body> <canvas width="600" height="300" id="canvas"></canvas> <img id="image" alt=""> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var image = new Image(); image.setAttribute('crossorigin', 'anonymous'); image.onload = function() { ctx.drawImage(image, 0, 0); document.getElementById('image').src = canvas.toDataURL('image/png'); }; image.src = 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3497300994,2503543630&fm=27&gp=0.jpg'; </script> </body>
對比上面兩段JS代碼,你會發(fā)現(xiàn)多了這一行:
image.setAttribute('crossorigin', 'anonymous');
就是這么簡單,完美的解決了!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解如何解決canvas圖片getImageData,toDataURL跨域問題
這篇文章主要介紹了詳解如何解決canvas圖片getImageData,toDataURL跨域問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-17