If the web page you want to draw contains a canvas image of an arc-shaped avatar, but the avatar itself is square, the required method is as follows:
First, get the coordinates, width and height of the avatar on the canvas: (I won’t go into detail here about how to get it)
let {avatarX, avatarY, avatarW, avatarH} = {20, 20, 80, 80};
Then just call the following function:
let Canvas = document.createElement('canvas');let ctx = Canvas.getContext(2d);let avatar = new Image();avatar.src = '../src/xx.png';avatar.onload = ( scaleBy = 2) => { circleImg(ctx, avatar, avatarX * scaleBy, avatarY * scaleBy, avatarW * scaleBy / 2);}// r: radius function circleImg(ctx, img, x, y, r) { ctx.save(); var d =2 * r; var cx = x + r; var cy = y + r; ctx.arc(cx, cy, r, 0, 2 * Math.PI); ctx.clip(); ctx.drawImage(img, x, y, d, d); ctx.restore();}
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.