2013-05-09 37 views
2

現在我有一個表單,我可以輸入一些文本並出現在畫布元素中,但是當我按下退格鍵時,文本不會消失了,當我重新鍵入文本時,它會出現在舊文本的頂部。在將文本從表單發送到canvas元素中的文本時,刪除文本不起作用

有沒有辦法讓canvas元素也響應刪除文字?

<!DOCTYPE html> 
<html> 


<title>dropIn Print Generator</title> 




<body> 
<h1>dropIn Print Generator</h1> 

<form method="post" action="run.php"> 
<p>brand name 
<input type="text" id="brand" onkeyup="showBrand(this.value)" /></p> 
<p>product name 
<input type="text" id="product" onkeyup="showProductName(this.value)" /></p> 
<p>product details 
<input type="text" id="details" onkeyup="showProductDetail(this.value)" /></p> 
<p>product sku 
<input type="text" id="sku" /></p> 
<p>product image 
<input type="file" id="image" /></p> 

</form> 

<canvas id="mainCanvas" width="400" height="600" style="border:1px solid #000000;"></canvas> 

<script> 
    var canvas = document.getElementById('mainCanvas'); 
    var context = canvas.getContext('2d'); 

    // begin upper shape 
    context.beginPath(); 
    context.moveTo(0, 0); 
    context.lineTo(400, 0); 
    context.lineTo(400, 300); 
    context.lineTo(380, 30); 
    context.lineTo(0, 50); 
    context.lineTo(0, 0); 

    // complete upper shape 
    context.closePath(); 
    context.lineWidth = 1; 
    context.strokeStyle = 'black'; 
    context.fillStyle = 'black'; 
    context.fill(); 
    context.stroke(); 

    // begin bottom shape 
    context.beginPath(); 
    context.moveTo(400, 600); 
    context.lineTo(200, 600); 
    context.lineTo(400, 585); 
    context.lineTo(400, 600); 

    // complete bottom shape 
    context.closePath(); 
    context.lineWidth = 1; 
    context.strokeStyle = 'black'; 
    context.fillStyle = 'black'; 
    context.fill(); 
    context.stroke(); 




    function showBrand(str){ 
     context.fillStyle = 'black'; 
     context.font = '20px sans-serif'; 
     context.textBaseline = 'bottom'; 
     context.fillText(str, 30, 100);   
     } 

    function showProductName(str){ 
     context.fillStyle = 'black'; 
     context.font = '30px sans-serif'; 
     context.textBaseline = 'bottom'; 
     context.fillText(str, 30, 135); 
     } 

    function showProductDetail(str){ 
     context.fillStyle = 'black'; 
     context.font = '20px sans-serif'; 
     context.textBaseline = 'bottom'; 
     context.fillText(str, 30, 160); 
     } 

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

回答

0

你需要清除你畫了一些新的文本到它每次之前在畫布上,否則你已經在畫布上繪製的任何東西都會保留,你會在它上面進行繪畫。

function clearCanvas() { 
    // Redraw the background color over the top of the old text to 'clear' it. 
    context.fillStyle = '#fff'; 
    context.fillRect(0, 0, canvas.width, canvas.height); 
} 

將此函數的調用添加到其他3個繪圖函數的開頭。

+0

它工作的很好,只有我將其他東西繪製到畫布中,所以每次我開始輸入時都會消失。在這裏唯一的方法是爲每件事物畫一幅畫布嗎? – Graviton 2013-05-09 10:43:12

+1

@Graviton是的,任何東西都不會自動從畫布上清除,你需要畫出它的頂部。在上面的代碼中,我只是在一切的頂部繪製了一個巨大的白色矩形。如果您的背景中有其他形狀,請將繪製它們的代碼放入'clearCanvas'函數中並調用一次以初始化畫布。 – 2013-05-09 10:47:35

相關問題