简体   繁体   中英

Save canvas in client side

JavaScript

if (!window.Clipboard) {
   var pasteCatcher = document.createElement("apDiv1");
   pasteCatcher.setAttribute("contenteditable", "");
   pasteCatcher.style.opacity = 0;
   document.body.appendChild(pasteCatcher);
   pasteCatcher.focus();
   document.addEventListener("click", function() { pasteCatcher.focus(); });
} 

window.addEventListener("paste", onPasteHandler);

function onPasteHandler(e)
{
    if(e.clipboardData) {
        var items = e.clipboardData.items;
        if(!items){
            alert("Image Not found");
        }
        for (var i = 0; i < items.length; ++i) {
        if (items[i].kind === 'file' && items[i].type === 'image/png') {
            var blob = items[i].getAsFile(),
                source = window.webkitURL.createObjectURL(blob);

            pastedImage = new Image();
            pastedImage.src = source;

            pasteData();
            }
        }
    }
}

function pasteData()
{
    drawCanvas = document.getElementById('drawCanvas1');
    ctx = drawCanvas.getContext( '2d' );
    ctx.clearRect(0, 0, 640,480);
    ctx.drawImage(pastedImage, 0, 0);
}

DIV

<div id="apDiv1" contenteditable='true'>Paste Test</div>

Above javascript will capture image from clipboard and paste in the DIV. How do I save the canvas in clientside. I'm not using any server so i need to save the canvas in client side. I found that canvas.toDataURL() will convert contents as a base64 encoded PNG file, but how do I do if i want the image save in my local. Let say, I have a folder Image in my C:// . How do I do if i want the image saved in particular folder.

Just set an html img element's src to canvas.toDataURL()

Then right-click-save-as.

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.fillRect(50,50,150,75);


    var theImage=document.getElementById("toImage");
    theImage.src=canvas.toDataURL();

Here's a complete example:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    ctx.fillRect(50,50,150,75);


    var theImage=document.getElementById("toImage");
    theImage.src=canvas.toDataURL();

}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
    <img id="toImage" width=300 height=300>
</body>
</html>

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