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