2014-04-01 52 views
0

我可以實現下載畫布作爲PNG文件,除非我使用drawImage()函數。我知道toDataURL()不允許外部圖像出現安全問題。但即使我使用託管在同一服務器上的本地映像,它仍然無法工作。不幸的是,我發現的解決方案都不適合我。如何下載畫布作爲圖像,其中包括drawImage()

<img id="soundc_icon" src="http://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_(2011).png"/> 
    <canvas width="500" height="300" id="canvas">Sorry, no canvas available</canvas> 
    <a id="download">Download as .PNG</a> 

    <script> 
    var canvas = document.getElementById('canvas'), 
    ctx = canvas.getContext('2d'); 
    var img = document.getElementById("soundc_icon"); 


    /** 
    * Demonstrates how to download a canvas an image with a single 
    * direct click on a link. 
    */ 
    function doCanvas() { 

     /* draw something */ 

     ctx.fillStyle = '#f90'; 
     ctx.fillRect(0, 0, canvas.width, canvas.height); 
     ctx.fillStyle = '#fff'; 
     ctx.font = '60px Lucida Grande'; 
     ctx.fillText('Code Project', 10, canvas.height/2 - 15); 
     ctx.font = '26px Lucida Grande'; 
     ctx.fillText('Click link below to save this as image', 15, canvas.height/2 + 35); 

     //I WANTO TO INCLUDE THIS AND STILL BE ABLE TO DOWNLOAD 
     //ctx.drawImage(img,10,10); 

    } 

    /** 
    * This is the function that will take care of image extracting and 
    * setting proper filename for the download. 
    * IMPORTANT: Call it from within a onclick event. 
    */ 
    function downloadCanvas(link, canvasId, filename) { 
     link.href = document.getElementById(canvasId).toDataURL(); 
     link.download = filename; 
    } 

    /** 
    * The event handler for the link's onclick event. We give THIS as a 
    * parameter (=the link element), ID of the canvas and a filename. 
    */ 
    document.getElementById('download').addEventListener('click', function() { 
                 downloadCanvas(this, 'canvas', 'test.png'); 
                 }, false); 

                 /** 
                  * Draw something to canvas 
                  */ 
    doCanvas(); 
     </script> 

回答

0

在服務器

配置您的服務器交付使用頭滿足CORS限制跨域圖像:

http://enable-cors.org/

在客戶

負載圖像使用克crossOrigin標誌設置爲匿名:

var img=new Image(); 
img.crossOrigin="anonymous"; 
img.onload=function(){ 
    ... 
    ctx.drawImage(img,10,10); 
} 
img.src="yourImage.png"; 

如果你想配置您的服務器之前測試客戶端,打開dropbox.com免費帳戶並把你的圖片在公共文件夾。您的公共文件夾符合CORS。

+0

感謝您的意見。但是當我使用源代碼(Dropbox中的公共鏈接)嘗試它時,仍然無法將其與我現有的代碼集成。我不知道哪個部分不起作用,因爲瀏覽器也不讓我看到錯誤。 – telvin

+0

看看這個半友善的鏈接:https://www.dropbox.com/help/16/en希望Dropbox在上市時不會刪除公共鏈接的能力 - 這是他們服務的最佳部分! – markE