Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a section of a canvas to a bitmap

I would like to capture a small part of a canvas as a bitmap. Is that possible? This is so that I can replace it after I draw another bitmap on that area. Once I am done with the bitmap I would like to replace the small bit of canvas that I drew on with the original piece.

Thanks!

like image 826
David C. Allen Avatar asked Dec 25 '10 23:12

David C. Allen


People also ask

How do I create a bitmap in canvas?

There is no way to extract the Bitmap out of a Canvas . The only way you can access it is to pass it yourself when creating the canvas like this new Canvas(myBitmap) and keep the reference.


1 Answers

The drawImage() method of contexts allows you to use an existing canvas as the source. It also allows you to specify sub-regions of the source "image" to draw. You can also create a new canvas element programmatically. Combine these, and you can create your own offscreen buffers and blit to/from them without needing to go through getImageData()/putImageData() or data URLs.

I've put an example of this online.

Note that while the example happens to append the dynamically-created canvas to the document so that you can see it (line 29 of the source), this is not necessary. Canvas elements created in the document function whether attached to the hierarchy or not.

In short:

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

Edit: I benchmarked this technique versus getImageData/putImageData; if speed is important, use drawImage for blitting regions. Here's what I saw:


(source: phrogz.net)

Benchmarks performed by saving and restoring a 125x180 region 10,000 times on OS X on a 2.8GHz Core i7 MacBook Pro. Your mileage may vary. Specifically, saving/restoring regions that are either much larger or smaller may result in different relative performance.

like image 172
Phrogz Avatar answered Sep 27 '22 17:09

Phrogz