开发者

Save/restore background area of HTML5 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 imag开发者_C百科e.
  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.


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜