Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

html - 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!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...