因为最近在做分享功能,需要用户的头像在微信小程序中,然后写下其他文字,如何在把正方形图片放到canvas,导成圆角。找了两个参考资料,分别是用.clip()和.clearRect()两种方法
但是它们的操作都是直接操作整张canvas,不满足我的需求。踩了一些坑,那么在一张canvas中画图片的圆角应该怎么做呢?写一个递归函数,用白色,在图像区域覆盖掉正方形多余的部分,让它看起来是一个圆。调整stepClear和stepClear += 0.5的数值,可以有效的减少图片的锯齿感。
参考如下代码
ctx.drawImage(url, x, y, w, h);
ctx.setFillStyle('white');
LeftArc(ctx, x, y , r, stepClear)
LeftArc: function (context, x, y, r, stepClear) {
var calcHeight = r - stepClear;
var calcWidth = Math.sqrt(r * r - calcHeight * calcHeight);
var rectWidth = r - calcWidth;
var rectheight = stepClear;
if (rectWidth > 0.1) {
context.fillRect(x - r, y - r, rectWidth, rectheight);
context.fillRect(x + calcWidth, y - r, rectWidth, rectheight);
context.fillRect(x - r, y + r - stepClear, rectWidth, rectheight);
context.fillRect(x + calcWidth, y + r - stepClear, rectWidth, rectheight);
stepClear += 0.5;
LeftArc(context, x, y, r, stepClear);
}
},
那么圆角就做好了,再加上其他的代码,就完成了任务要求。大家对我们的小程序感兴趣,可以扫码体验一下哦!
结果图