Save / restore HTML5 canvas background size

I am using HTML5 canvas as follows:

  • Display an image that fills the canvas area.
  • Display a black text box on it.
  • When you click on a text label, select it by drawing filled red rectangular + white text.

I have this part working perfectly. Now I want to remove the red rectangle and restore the original background of the image that was behind it. I am new to canvas and have read a fair amount, however I don’t see how to do it. Nevertheless, I am sure that this should be quite simple.

+3
source share
3 answers

I think there are some ways ...

Redraw all content after releasing clicks

, .

drawImage 9 , , .

,

getImageData putImageData 2D-. ( , , .)

:

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);

, , (20,30) (180,70) , :

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);

, , , "" .

+6

Stack Overflow , , . :

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;
}
+2
function draw(e){
    ctx.drawImage(img, 0, 0);
    if(e){
        ctx.fillStyle='red';
        ctx.fillRect(5, 5, 50, 15);
        ctx.fillStyle='white';
    }else{
        ctx.fillStyle='black';
    }
    ctx.fillText('Label', 10, 17);
}
draw();
document.onclick=draw;
0
source

All Articles