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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…