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

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

问题描述

我想捕捉画布作为位图的一小部分。那可能吗?这是为了让我可以取代它后,我吸取这方面的另一个位图。一旦我与位图做我想换成帆布的小点点,我画了与原片。

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.

谢谢!

推荐答案

上下文的的drawImage()方法,可以使用现有的帆布作为源。它还允许你指定源形象的子区域绘制。您也可以通过编程创建一个新的canvas元素。结合这些,你可以创建自己的屏幕外的缓冲区和位图传送到/从他们无需通过 getImageData()/ putImageData()或数据的URL。

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.

我已经把一个例如本次网上的。

请注意,虽然这个例子恰好追加动态创建的画布文档,以便你可以看到它(源的第29行),这是没有必要的。在文档功能创建的画布元素是否连接到层次或没有。

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.

在短:

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

修改:我基准这种技术与 getImageData / putImageData ;如果速度是重要的,使用的drawImage 的块传输的区域。这是我看到的:

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

通过保存和2.8GHz的酷睿i7的MacBook Pro在OS X恢复125x180区域10,000次进行基准测试。你的情况可能会有所不同。具体地讲,保存/恢复是要么多较大或较小的区域可导致不同的相对性能。

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

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