HTML Canvas - 动态更改文本

时间:2015-08-07 16:44:51

标签: javascript jquery html canvas

当我在输入文本字段中输入时,我正在尝试更改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);
    });

4 个答案:

答案 0 :(得分:2)

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

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>

答案 1 :(得分:1)

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

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

更新

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

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

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

答案 2 :(得分:0)

尝试使用此

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

按画布限制,您必须重绘整个画布才能更新其内容

答案 3 :(得分:0)

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

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