Reputation: 1675
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.
Upvotes: 0
Views: 1283
Reputation:
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:
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
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
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.
Upvotes: 3