0

我正在画布上绘制图像。然后我想保存图像。我尝试了 canvas.toDataURL("image/png"),但我意识到由于安全原因我不能使用 toDataURL()。但是,我必须保存图像。如何保存图像?

这是我的示例源代码。

window.onload = function(){
    var oCanvas = document.getElementById("work_pallet");
    var oContext = oCanvas.getContext("2d");

    var imageObj = new Image();                                 
    imageObj.onload = function() {
        oContext.drawImage(imageObj, 0, 0, oCanvas.width, oCanvas.height);      
    }
    imageObj.src = "http://www.ehanftp.co.kr/ueditor/data/20130204/mini2/guide.pdf_1.png";


    function saveImage(){
        var bRes = false;
        alert(oCanvas.toDataURL());
        bRes = Canvas2Image.saveAsPNG(oCanvas);
        if (!bRes) {
            alert("Sorry, this browser is not capable of saving image!");
            return false;
        }
    }

    document.getElementById("saveCanvasImage").onclick = function() {
        saveImage();
    }
}
4

1 回答 1

1

例子:

<html>
    <head>
        <script src="http://www.nihilogic.dk/labs/canvas2image/canvas2image.js"></script>
        <script>
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25,25,100,100); 
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
            }

            function to_image(){
                var canvas = document.getElementById("thecanvas");
                document.getElementById("theimage").src = canvas.toDataURL();
                Canvas2Image.saveAsPNG(canvas);
            }
        </script>
    </head>
    <body onload="draw()">
        <canvas width=200 height=200 id="thecanvas"></canvas>
        <div><button onclick="to_image()">Draw to Image</button></div>
        <image id="theimage"></image>
    </body>
</html>
于 2013-02-28T11:51:32.640 回答