Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Canvas - change text dynamically

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);
    });
like image 598
SNos Avatar asked Apr 28 '26 21:04

SNos


2 Answers

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

UPDATE

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.

like image 70
Shashwat Black Avatar answered Apr 30 '26 09:04

Shashwat Black


You can save the state of the canvas, update the content, then restore it via:

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>
like image 31
j08691 Avatar answered Apr 30 '26 09:04

j08691