HTML Canvas – 动态更改文本

当我在输入文本字段中输入时,我正在尝试更改htmlcanvas上的文本。

我可以添加文本,但是,如果我删除并再次输入,则新文本将添加到旧文本的顶部。

的jsfiddle

document.getElementById('title').addEventListener('keyup', function() { var stringTitle = document.getElementById('title').value; console.log(stringTitle); ctx.fillStyle = '#fff'; ctx.font = '60px sans-serif'; var text_title = stringTitle; ctx.fillText(stringTitle, 15, canvas.height / 2 + 35); }); 

这很有效。 您只需在每次更新时清除canvas。

 document.getElementById('title').addEventListener('keyup', function() { var stringTitle = document.getElementById('title').value; console.log(stringTitle); ctx.fillStyle = '#0e70d1'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#fff'; ctx.font = '60px sans-serif'; var text_title = stringTitle; ctx.fillText(stringTitle, 15, canvas.height / 2 + 35); }); 

UPDATE

如果您只想更新文本所在的区域,您可以这样做,

 ctx.fillRect(0, 130, canvas.width, 70); 

另一种方法是,跟踪文本以及canvas中的其他对象并刷新整个canvas。 这并不像你想象的那样是内存密集型的。 如果需要,还可以通过将先前的字符串与新字符串进行比较,仅在文本被删除(完全或部分)时重置canvas。

您可以保存canvas的状态,更新内容,然后通过以下方式恢复它:

 var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); ctx.fillStyle = '#0e70d1'; ctx.fillRect(0, 0, canvas.width, canvas.height); document.getElementById('title').addEventListener('keyup', function () { ctx.save(); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillRect(0, 0, canvas.width, canvas.height); var stringTitle = document.getElementById('title').value; ctx.fillStyle = '#fff'; ctx.font = '60px sans-serif'; var text_title = stringTitle; ctx.fillText(stringTitle, 15, canvas.height / 2 + 35); ctx.restore(); }); 
 Sorry, no canvas available   

尝试用这个替换最后几行

 ctx.fillStyle = '#0e70d1'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#fff'; ctx.fillText(stringTitle, 15, canvas.height / 2 + 35); 

通过canvas限制,您必须重绘整个canvas才能更新其内容

我会将您的文本添加到数组中,然后在每次键入和重绘所有文本后清除canvas。

由于字母宽度不同,空格和退格也不同,因此您无法确定要清除要删除的字母。