0

drawImage() 関数を使用しない限り、キャンバスを png ファイルとしてダウンロードできます。toDataURL() は、セキュリティ上の問題から外部画像を許可していないことを知っています。しかし、同じサーバーでホストされているローカル イメージを使用しても、まだ機能しません。残念ながら、私が見つけた解決策はどれもうまくいきませんでした。

    <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>
4

1 に答える 1

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 に準拠しています。

于 2014-04-01T14:57:11.060 に答える