HTML Canvas - 动态更改文本 [英] HTML Canvas - change text dynamically

查看:937
本文介绍了HTML Canvas - 动态更改文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在输入文本字段中键入内容时,我正在尝试更改html画布上的文本。

I am trying to change the text on my html canvas while I type inside an input text field.

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

I can add the text however, if I delete and type again the new text is added on the top of the old one.

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


推荐答案

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

This works. You just clear the canvas every time it's updated.

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

更新

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

In case you only want to update the area where the text is, you can do just that,

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

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

Another approach would be, keeping track of the text as well as other objects in the canvas and refreshing the entire canvas. This is not as memory intensive as you'd think. If you want, you could also reset the canvas only when the text has been deleted (completely or partially), by comparing the previous string with new one.

这篇关于HTML Canvas - 动态更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆