canvas 图片圆角问题


引子

近期的工作中,是继 canvas 设置边框问题 之后碰到的第 4 个问题。

图片圆角问题

如果只是想要显示圆角的效果,设置 border-radius 就可以了,但如果要让 canvas 合成的图片显示为圆角,这种 css 方式不行。这是示例,扫描访问二维码如下。

19-canvas-border-radius

在网上查询资料,发现同样的问题,解决的方式是用 canvas 的裁剪功能。

解决方法

先画布上画一个有圆角的矩形,然后使用裁剪的方式 clip()

// 生成有圆角的矩形
function drawRoundedRect(cxt, x, y, width, height, radius) {
  cxt.beginPath();
  cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
  cxt.lineTo(width - radius + x, y);
  cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
  cxt.lineTo(width + x, height + y - radius);
  cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);
  cxt.lineTo(radius + x, height + y);
  cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);
  cxt.closePath();
}

这是示例,扫描访问二维码如下。

19-canvas-radius-clip

参考资料


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM