Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using HTML5 canvas as follows:

  1. Display an image that fills the canvas area.
  2. Display a black text label over the image.
  3. On click of the text label highlight it by drawing a filled red rect + white text.

I have that part all working fine. Now what I want to do is remove the red rect and restore the image background that was originally behind it. I'm new to canvas and have read a fair amount, however I can't see how to do this. That said I am sure it must be quite simple.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
342 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think there are some ways...

Redraw all stuff after the click release

This is simple but not really efficient.

Redraw only the altered part

drawImage with 9 arguments to redraw only the altered background image part, then redraw the black text over.

Save image data before click and then restore it

This uses getImageData and putImageData of the 2D context. (Not sure that it's widely implemented though.)

Here the specification:

ImageData getImageData(in double sx, in double sy, in double sw, in double sh);
void putImageData(in ImageData imagedata, in double dx, in double dy, in optional double dirtyX, in double dirtyY, in double dirtyWidth, in double dirtyHeight);

So for instance if the altered part is in the rect from (20,30) to (180,70) pixels, simply do:

var ctx = canvas.getContext("2d");
var saved_rect = ctx.getImageData(20, 30, 160, 40);
// highlight the image part ...

// restore the altered part
ctx.putImageData(saved_rect, 20, 30);

Use two superposed canvas

The second canvas, positioned over the first, will hold the red rect and the white text, and will be cleared when you want to "restore" the original image.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...