0

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 id="apDiv1" contenteditable='true'>Paste Test</div>

上面的 javascript 将从剪贴板捕获图像并粘贴到 DIV 中。如何将画布保存在客户端。我没有使用任何服务器,所以我需要将画布保存在客户端。我发现这canvas.toDataURL()会将内容转换为 base64 编码的 PNG 文件,但是如果我想将图像保存在本地,我该怎么办。比方说,我的C ://中有一个文件夹Image。如果我想将图像保存在特定文件夹中,我该怎么办。

4

1 回答 1

1

只需将 html img 元素的 src 设置为 canvas.toDataURL()

然后右键另存为。

    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();

这是一个完整的例子:

<!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>
于 2013-07-17T06:08:22.543 回答