2016-07-27 43 views
0

我試圖使用keydown和keyup其顯示在畫布上,但是當我按'退格'或刪除文本仍然不刪除。HTML輸入到畫布接受退格

var canvas = document.getElementById('myCanvas'); 
 
var context = canvas.getContext('2d'); 
 

 
// do cool things with the context 
 
context.font = '40pt Calibri'; 
 
context.fillStyle = 'blue'; 
 
$('input').keydown(function(e){ 
 
     
 
    if(e.keyCode==8) 
 
    { 
 
    var newvalue = $(this).val(); 
 
    context.fillText(newvalue, 150, 100); 
 
    } 
 
}); 
 
$('input').keyup(function(){ 
 
    context.fillText($(this).val(), 150, 100); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<input type="text" value=""> 
 
<canvas id="myCanvas" width="578" height="200"></canvas>

+0

畫布不象是工作,你需要清除和重繪(或添加到圖紙)。畫布在形式上就像一幅畫,你正在畫上文字 - 它不是現場模仿你在做什麼。您可能需要使用'canvasContext.clearRect(0,0,canvas.width,canvas.height)'來清除文本,然後在文本發生更改後重新繪製文本。現在你一遍又一遍地繪製相同的文字。 – somethinghere

回答

0

您需要重繪之前清除你的畫布,以消除任何已經填充像素:

context.clearRect(0, 0, canvas.width, canvas.height); 

正如你可能已經注意到,它並沒有刪除你的性格,但是如果您鍵入另一個字符,它也會覆蓋上一個字符 - 這就是爲什麼您需要在重繪前清除的原因。

var canvas = document.getElementById('myCanvas'); 
 
var context = canvas.getContext('2d'); 
 

 
// do cool things with the context 
 
context.font = '40pt Calibri'; 
 
context.fillStyle = 'blue'; 
 
$('input').keydown(function(e){ 
 
    if(e.keyCode==8){ 
 
    var newvalue = $(this).val(); 
 
    context.clearRect(0,0,canvas.width,canvas.height); 
 
    context.fillText(newvalue, 150, 100); 
 
    } 
 
}); 
 
$('input').keyup(function(){ 
 
    context.clearRect(0,0,canvas.width,canvas.height); 
 
    context.fillText($(this).val(), 150, 100); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<input type="text" value=""> 
 
<canvas id="myCanvas" width="578" height="200"></canvas>

+0

謝謝,它的作品 –

0

請檢查下面的代碼片段,您可以使用clearRect(0,0,canvas.width,canvas.height)清除畫布。
我想你並不需要兩個keyup & keydown事件。

var canvas = document.getElementById('myCanvas'); 
 
var context = canvas.getContext('2d'); 
 

 
// do cool things with the context 
 
context.font = '40pt Calibri'; 
 
context.fillStyle = 'blue'; 
 

 
$('input').keyup(function() { 
 
    context.clearRect(0, 0, canvas.width,canvas.height); 
 
    context.fillText($(this).val(), 150, 100); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" value=""> 
 
<canvas id="myCanvas" width="578" height="200"></canvas>