當(dāng)在canvas中繪制一張外鏈圖片時(shí),我們會(huì)遇到一個(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í),你會(huì)發(fā)現(xiàn)這個(gè)問題:
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
這是受限于 CORS 策略,會(huì)存在跨域問題,雖然可以使用圖像,但是繪制到畫布上會(huì)污染畫布,一旦一個(gè)畫布被污染,就無法提取畫布的數(shù)據(jù),比如無法使用使用畫布toBlob(),toDataURL(),或getImageData()方法;當(dāng)使用這些方法的時(shí)候 會(huì)拋出上面的安全錯(cuò)誤
這是一個(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>
對(duì)比上面兩段JS代碼,你會(huì)發(fā)現(xiàn)多了這一行:
image.setAttribute('crossorigin', 'anonymous');
就是這么簡單,完美的解決了!
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。