最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - html5 canvas - Update text - Stack Overflow

programmeradmin3浏览0评论

Here's my project: /

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?

Here's my project: http://jsfiddle/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?

Share Improve this question edited Jul 20, 2012 at 20:27 JSW189 6,33512 gold badges46 silver badges73 bronze badges asked Jun 6, 2012 at 15:48 larin555larin555 1,6994 gold badges28 silver badges43 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 ponents of your drawing and allow you to remove or alter specific elements.

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 pletely 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).

发布评论

评论列表(0)

  1. 暂无评论