I am using HTML5 canvas as follows:
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...
This is simple but not really efficient.
drawImage with 9 arguments to redraw only the altered background image part, then redraw the black text over.
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);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With