Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.


方案2親測有效,簡單粗暴

解決方案1.

如果想使用toDataURL()生成圖片文件的話,在canvas繪圖過程中使用的圖片應該是當前域下的。

解決方案2.

訪問的服務器允許,資源跨域使用,也就是說設置了CORS跨域配置,Access-Control-Allow-Origin

然后在客戶端訪問圖片資源的時候

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

實例說明:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <link href="../scripts/Bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet" />
    <script src="../scripts/jquery-1.11.3.min.js"></script>
    <script src="../scripts/Bootstrap-3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <img src="http://www.gongjuji.net/favicon.ico"  crossorigin="anonymous"/>
    <canvas id="canvasOne" width="200" height="200"></canvas>
</div>
<script>
    /*
    * 將canvas圖片轉換成圖片,上傳到服務器
    */
    var canvas = document.getElementById('canvasOne');
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'red';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //添加外網圖片
    var img = new Image();
    //設置圖片跨域訪問
    //img.setAttribute('crossOrigin', 'anonymous');
    img.onload = function () {
        //畫圖
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var data = canvas.toDataURL('image/jpeg');
        alert(data);
    }
    //使用外網圖片
    img.src = 'http://www.gongjuji.net/favicon.ico';
</script>
</body>
</html> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM