如何将画布的一部分捕获到位图 [英] How to capture a section of a canvas to a bitmap

查看:29
本文介绍了如何将画布的一部分捕获到位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将画布的一小部分捕获为位图.那可能吗?这样我就可以在该区域上绘制另一个位图后替换它.完成位图后,我想用原始画布替换我绘制的一小块画布.

谢谢!

解决方案

上下文的 drawImage() 方法允许您使用现有画布作为源.它还允许您指定要绘制的源图像"的子区域.您还可以以编程方式创建新的画布元素.将这些结合起来,您就可以创建自己的屏幕外缓冲区,并且无需通过 getImageData()/putImageData() 或数据 URL.

我在网上放了一个
(来源:phrogz.net)

通过在 2.8GHz Core i7 MacBook Pro 上的 OS X 上保存和恢复 125x180 区域 10,000 次来执行基准测试.你的旅费可能会改变.具体来说,保存/恢复更大或更小的区域可能会导致不同的相对性能.

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!

解决方案

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.

这篇关于如何将画布的一部分捕获到位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆