簡體   English   中英

HTML Canvas-動態更改文本

[英]HTML Canvas - change text dynamically

我在輸入文本字段中鍵入內容時嘗試更改html畫布上的文本。

但是,我可以添加文本,如果我刪除並再次鍵入,則新文本將添加到舊文本的頂部。

的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);
    });

您可以保存畫布的狀態,更新內容,然后通過以下方式還原它:

 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(); }); 
 <canvas width="500" height="300" id="canvas">Sorry, no canvas available</canvas> <input type="text" id="title" placeholder="Your Title" /> </br> 

這可行。 您只需在每次更新時清除畫布即可。

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);

另一種方法是,跟蹤文本以及畫布中的其他對象,並刷新整個畫布。 這並不像您想的那樣占用大量內存。 如果需要,也可以僅通過刪除文本(全部或部分刪除)來重置畫布,方法是將前一個字符串與新字符串進行比較。

嘗試用此替換最后幾行

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

受畫布限制,您必須重新繪制整個畫布才能更新其內容

我會將您的文本添加到數組中,然后在每次鍵入並重新繪制所有文本后清除畫布。

由於字母的寬度不同,空格和退格鍵也不同,因此無法確定您會完全清除要刪除的字母。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM