如何将图像保存到画布上?

时间:2013-02-28 11:47:02

标签: javascript image html5 canvas save

我正在画布上画一个图像。然后我想保存图像。我试过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();
    }
}

1 个答案:

答案 0 :(得分: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>