引子

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

图片圆角问题

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

canvas 图片圆角问题

在网上查询资料,发现同样的问题,解决的方式是用 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();
}

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

canvas 图片圆角问题

参考资料

相关文章:

  • 2021-07-31
  • 2022-12-23
  • 2021-05-28
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2022-01-19
  • 2021-12-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2022-12-23
  • 2021-06-18
  • 2021-09-26
  • 2022-02-16
相关资源
相似解决方案