canvas替代putImageData

canvas替代putImageData

本文介绍了HTML5 canvas替代putImageData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了分别使用 getImageData putImageData 之外,还有另一种方法可以将像素区域从(例如)画布A复制到画布B中。 code>。

is there another method to copy region of pixels from (let say) Canvas A to canvas B other than using respectively getImageData and putImageData.

同样,当复制到画布B时,它应该像油漆刷一样舍入而不是矩形。

also, when copy to Canvas B it should be rounded like a paint brush not rectangle.

推荐答案

要将内容从一个画布复制到另一个画布,可以使用 drawImage()。此方法可以将图像,画布或视频作为图像源。

To copy content from one canvas to another you can use drawImage(). This method can take image, canvas or video as image source.

要绘制圆形,有两种方法:

To draw rounded there are two ways:

此方法假定目标画布为空。首先在目标画布上设置一个圆( ctx 是画布B /目标/目标的上下文):

This method assumes the target canvas is empty. First set up a circle on target canvas (ctx being context for canvas B/target/destination):

ctx.beginPath();                              // clear previous path (if any)
ctx.arc(centerX, centerY, radius, 0, 6.283);  // 1) draw a full arc on target
ctx.fill();                                   // fill with default color

这将绘制一个圆圈并填充它(确保Alpha通道设置为完整)。然后更改并在画布A中绘制:

This will draw a circle and fill it (make sure alpha channel is set to full). Then change composite mode and draw in canvas A:

ctx.globalCompositeOperation = 'source-in';   // change comp. mode
ctx.drawImage(canvasA, 0, 0);                 // draw canvas A
ctx.globalCompositeOperation = 'source-over'; // reset to default

FIDDLE

这类似于方法A但目标画布可能包含数据。此方法的缺点是某些浏览器会留下粗糙(锯齿)的边缘。基础很相似-首先将完整的弧定义为路径,但不填充它:

This is similar to method A but target canvas may contain data. The cons with this method is that some browsers will leave a rough (aliased) edge. The basis is similar - first define a full arc as path but don't fill it:

ctx.beginPath();
ctx.save();                                   // for removing clip later
ctx.arc(centerX, centerY, radius, 0, 6.283);  // draw a full arc on target
ctx.clip();                                   // define clip

ctx.drawImage(canvasA, 0, 0);                 // draw canvas A
ctx.restore();                                // remove clip

FIDDLE

如果要在绘制到画布B时更改画布A的大小和位置,请查看查看其附带的选项。

If you want to change the size and position of canvas A when drawn to canvas B then look at the documentation for drawImage() to see the options it comes with.

这篇关于HTML5 canvas替代putImageData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 07:47