Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save/restore background area of HTML5 Canvas

Tags:

html

canvas

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.

like image 588
nevf Avatar asked Dec 12 '22 16:12

nevf


2 Answers

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.

like image 105
Pierre Avatar answered Dec 21 '22 22:12

Pierre


For another Stack Overflow question I created an example showing how to save and restore a section of a canvas. In summary:

function copyCanvasRegionToBuffer( canvas, x, y, w, h, bufferCanvas ){
  if (!bufferCanvas) bufferCanvas = document.createElement('canvas');
  bufferCanvas.width  = w;
  bufferCanvas.height = h;
  bufferCanvas.getContext('2d').drawImage( canvas, x, y, w, h, 0, 0, w, h );
  return bufferCanvas;
}
like image 43
Phrogz Avatar answered Dec 22 '22 00:12

Phrogz