2017-07-31 123 views
0

這是一個用帆布將HTML轉換成圖像的代碼.. 我有一個問題一樣,當我點擊預覽按鈕是越來越填充的圖像,但如果再次嘗試點擊預覽按鈕,兩個預覽圖像出現。如何刪除畫布

如何刪除第一個預覽?

<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"></script> 
</head> 
<body> 
<div id="html-content-holder" style="background-color: #F0F0F1; color: #00cc65; width: 500px; 
     padding-left: 25px; padding-top: 10px;"> 
     <strong>Codepedia.info</strong><hr/> 
     <h3 style="color: #3e4b51;"> 
      Html to canvas, and canvas to proper image 
     </h3> 
     <p style="color: #3e4b51;"> 
      <b>Codepedia.info</b> is a programming blog. Tutorials focused on Programming ASP.Net, 
      C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, 
      Web Design, Software</p> 
     <p style="color: #3e4b51;"> 
      <b>html2canvas</b> script allows you to take "screenshots" of webpages or parts 
      of it, directly on the users browser. The screenshot is based on the DOM and as 
      such may not be 100% accurate to the real representation. 
     </p> 
    </div> 
    <input id="btn-Preview-Image" type="button" value="Preview"/> 
    <a id="btn-Convert-Html2Image" href="#">Download</a> 
    <br/> 
    <h3>Preview :</h3> 
    <div id="previewImage"> 
    </div> 


<script> 
$(document).ready(function(){ 


var element = $("#html-content-holder"); // global variable 
var getCanvas; // global variable 

    $("#btn-Preview-Image").on('click', function() { 
     html2canvas(element, { 
     onrendered: function (canvas) { 
       $("#previewImage").append(canvas); 
       getCanvas = canvas; 
      } 
     }); 
    }); 

    $("#btn-Convert-Html2Image").on('click', function() { 
    var imgageData = getCanvas.toDataURL("image/png"); 
    // Now browser starts downloading it instead of just showing it 
    var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream"); 
    $("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData); 
    }); 

}); 

</script> 
</body> 
</html> 

回答

1

你可能想創建一個新的預覽之前刪除從#previewImage DIV任何現有的子div中,因此只使用$("#previewImage").empty();調用html2canvas之前,或將圖像保存到磁盤之後。

例如:

$("#btn-Preview-Image").on('click', function() { 
    $("#previewImage").empty(); // <-- this 
    html2canvas(element, { 
    onrendered: function (canvas) { 
      $("#previewImage").append(canvas); 
      getCanvas = canvas; 
     } 
    }); 
}); 
+0

ü感謝這麼多......它幫助.. :) – Questions

+0

一個疑問,我添加了DIV中的一些按鈕後,該分區爲空的設置,然後按鈕不顯示 – Questions

+0

@Questions:如果你只想刪除'canvas'元素,你可以使用'$(「#previewImage canvas」)。remove()'來代替。 – Groo