简体   繁体   中英

How to save canvas image in disk?

in my application, i merge two images as single image on canvas in html.now i want to save that canvas image into my disk. but the code works fine only for 2 times, after that it didn't save the image.i tried to find the error but got nothing.Please help me to sort it out.

<p>Image to use:</p>

<img id="scream" src="img_the_scream.jpg" alt="The Scream"
width="220" height="277">
<img id="scream2" src="img_the_scream.jpg" alt="The Scream"
width="220" height="277">


<p>Canvas to fill:</p>

<canvas id="canvas" width="800" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<p><button onclick="myCanvas()">Try it</button></p>

<script>
function myCanvas() {
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("scream");
    ctx.drawImage(img,10,10);

 var img = document.getElementById("scream2");
    ctx.drawImage(img,210,10);
}
</script>
        <h1>Save Image</h1>


        <button type="button" onclick="saveImage()">save image</button>
        <script type="text/javascript">
            function saveImage() {
                var ua = window.navigator.userAgent;

                if (ua.indexOf("Chrome") > 0) {
                    // save image without file type
                    var canvas = document.getElementById("canvas");
                    document.location.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

                    // save image as png
                    var link = document.createElement('a');
                    link.download = "test1.png";
                    link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");;
                    link.click();
                }
                else {
                    alert("Please use Chrome");
                }
            }
        </script>

您可以右键单击画布并将图像另存为。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM