Save/restore background area of HTML5 Canvas

前端 未结 3 1994
攒了一身酷
攒了一身酷 2020-12-10 20:41

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 t
相关标签:
3条回答
  • 2020-12-10 20:41
    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 讨论(0)
  • 2020-12-10 20:43

    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.

    0 讨论(0)
  • 2020-12-10 20:58

    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;
    }
    
    0 讨论(0)
提交回复
热议问题