HTML5 canvas alternative to putImageData

二次信任 提交于 2019-12-25 02:29:40

问题


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

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


回答1:


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:

Method A - Use composite mode

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

1) 6.283 = 2 x PI

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

Method B - Use clipping

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

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.



来源:https://stackoverflow.com/questions/23559848/html5-canvas-alternative-to-putimagedata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!