larin555
larin555

Reputation: 1689

html5 canvas - Update text

Here's my project: http://jsfiddle.net/fknjz/17/

When I type in the textboxes under the canvas and click "UPDATE", it works and add the text in the canvas. But every time I click UPDATE, it adds the textbox content over the content typed before. So the text in the canvas starts stacking up on each other.

What I need is to modify the text in the Canvas so that when I click UPDATE, it actually updates the text, not create a new text line of text over the old one.

Any idea how to do it?

Upvotes: 2

Views: 3736

Answers (2)

net.uk.sweet
net.uk.sweet

Reputation: 12431

You could clear the canvas like so:

canvas.width = canvas.width;

See updated fiddle. Note that you need to redraw the image each time since the canvas is completely cleared.

Or, as suggested by apsillers and Joceyln, use the clearRect method of canvas. This, however, will require you to calculate the area of the rectangle you want to clear which may need to vary depending on the amount of text the user enters and will remove sections of the image you have drawn in the background (which may not be an issue if it's always going to be a white background).

Upvotes: 1

apsillers
apsillers

Reputation: 115940

Remember that the canvas is just a bunch of pixels: when you make that call to fillText, the canvas doesn't see characters, it sees a set of pixels. Furthermore, that set of pixels, as a distinct group, is immediately lost -- there's no way to ask the canvas, "Please remove that specific set of pixels I just added."

Your options are:

  • Using clearRect to wipe away a rectangular section of your drawing.

  • Using canvas.width = canvas.width; to reinitialize the pixel state of the canvas. This requires you to redraw the entire canvas, whereas clearRect gives you more precision.

For future work, you might consider using a canvas drawing library that can maintain state about the components of your drawing and allow you to remove or alter specific elements.

Upvotes: 8

Related Questions