I have put text on an image in a <canvas>
tag (the text was taken from an input box).
Now if I put a new text on the <canvas>
, it is imposed on the previous text. How do I clear the existing text on the canvas before putting in the new text?
I have tried resetting the canvas by assigning canvas.width
but the text stays on. Any help people?
The fillText() method draws filled text on the canvas. If you want to break lines you can do this by splitting the text at the new lines and calling the filltext() multiple times.
In the canvas toolbar, click the Select/Transform tool, then double-click text in the canvas. In the Layer's list, select a text layer, then in the Text editor (at the bottom of the Text Inspector's Format pane), drag within or double-click text.
Use: context. clearRect(0, 0, canvas. width, canvas. height);
Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText().
If you know you're going to be adding and removing text a lot, it might make sense to keep track of the old text. Then you could just use this:
context.fillStyle = '#ffffff'; // or whatever color the background is.
context.fillText(oldText, xCoordinate, yCoordinate);
context.fillStyle = '#000000'; // or whatever color the text should be.
context.fillText(newText, xCoordinate, yCoordinate);
This way you don't have to redraw the whole canvas every time.
You use context.clearRect(), but first you have to figure out the rectangle to clear. This is based off a number of factors, such as the size of the text and the textAlign property of the canvas context when the text was originally drawn. The code below would be for the draw method of a object that draws text into a canvas context, as such it has properties for x, y, text size, horizontal alignment etc. Note that we always store the last piece of text drawn so we can clear an appropriately sized rectangle when the value is next changed.
this.draw = function() {
var metrics = this.ctx.measureText(this.lastValue),
rect = {
x: 0,
y: this.y - this.textSize / 2,
width: metrics.width,
height: this.textSize,
};
switch(this.hAlign) {
case 'center':
rect.x = this.x - metrics.width / 2;
break;
case 'left':
rect.x = this.x;
break;
case 'right':
rect.x = this.x - metrics.width;
break;
}
this.ctx.clearRect(rect.x, rect.y, rect.width, rect.height);
this.ctx.font = this.weight + ' ' + this.textSize + ' ' + this.font;
this.ctx.textAlign = this.hAlign;
this.ctx.fillText(this.value, this.x, this.y);
this.lastValue = this.value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With