2013-07-17 68 views
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

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

以上的JavaScript將剪貼板中的圖像捕獲,並在DIV粘貼。如何在客戶端保存畫布。我沒有使用任何服務器,所以我需要將畫布保存在客戶端。 我發現canvas.toDataURL()會將內容轉換爲base64編碼的PNG文件,但如果我想要保存在本地的圖像,該怎麼辦。比方說,我有一個文件夾圖片在我的C://。如果我想將圖像保存在特定文件夾中,我該怎麼辦?

回答

2

只需設置一個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> 
+0

在圖像保存。如果我想保存在C:// Images文件夾中。 –

+0

當你右鍵點擊圖片時,你會得到一個上下文菜單。其中一個上下文菜單選項是「圖片另存爲」(這個措辭因瀏覽器而異)。然後導航到您的c:images文件夾,然後按保存按鈕。出於安全原因,瀏覽器不允許將文件編程保存到本地系統,但大多數用戶都熟悉和習慣於將圖像保存到本地文件系統的右鍵單擊 - 保存方式。 – markE

+0

我的用戶將粘貼屏幕截圖。我需要在用戶粘貼圖像後自動保存。如果用戶點擊並保存,圖像將保存在用戶本地。我想要它保存服務器,以便管理員可以恢復。 –