HTML Canvas clip and putImageData

I have a canvas with a large image in the background and a smaller circular image in front of it. I achieved this round image effect using a clip this way

ctx.save(); ctx.beginPath(); ctx.arc(x,y,r,0,Math.PI*2, true); ctx.closePath(); ctx.clip(); ctx.drawImage(img,xr,yr,2*r,2*r); // draw the image ctx.restore(); 

then I want to rotate the circular image, so I use the second context and rotate and redraw like this

 backCanvas=document.createElement('canvas'); backContext=backCanvas.getContext('2d'); backCanvas.width=w; backCanvas.height=h; backContext.translate(w/2,h/2); backContext.rotate(a); backContext.drawImage(img,-w/2,-h/2,w,h); var imgData=backContext.getImageData(0,0,w,h); ctx.save(); ctx.beginPath(); ctx.arc(x,y,r,0,Math.PI*2, true); ctx.closePath(); ctx.clip(); ctx.putImageData(imgData,x,y); ctx.restore(); 

But it happens that a black-and-white background is copied from the back of the canvas, and the clip cannot “fix” it.

Any help would be appreciated

+1
source share
1 answer

According to specs ,

The current path, transformation matrix, shadow attributes, global alpha, clipping region, and global layout operator should not affect the getImageData () and putImageData () methods.

In your case, why are you using additional manipulations with the canvas and pixels? Why not just

 ctx.save(); ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI*2, true); ctx.closePath(); ctx.clip(); ctx.translate(x, y); ctx.drawImage(img, -r, -r, 2*r, 2*r); // not restoring context here, saving the clipping region and translation matrix // ... here goes the second part, wherever it is: ctx.save(); ctx.rotate(a); ctx.drawImage(img, -r, -r, 2*r, 2*r); ctx.restore(); 
+5
source

Source: https://habr.com/ru/post/887662/


All Articles