Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
607 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...