RoundedRectangle in Canvas

We use fillRect to draw a Rectangle in canvas, but fillRect doesn't support rounded corners. How can we draw a RoundedRectangle in canvas just like the border-radius in CSS.

QuadraticCurve

Use quadraticCurveTo to draw rounded corner line.

export default function roundRectByQuadraticCurve(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number = 0
) {
  ctx.beginPath()
  ctx.moveTo(x + radius, y)
  ctx.lineTo(x + width - radius, y)
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
  ctx.lineTo(x + width, y + height - radius)
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
  ctx.lineTo(x + radius, y + height)
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
  ctx.lineTo(x, y + radius)
  ctx.quadraticCurveTo(x, y, x + radius, y)
  ctx.closePath()
}

Arc

Use arcTo to draw rounded corner line.

export default function roundRectByArc(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number = 0
) {
  ctx.beginPath()
  ctx.moveTo(x + radius, y)
  ctx.arcTo(x + width, y, x + width, y + height, radius)
  ctx.arcTo(x + width, y + height, x, y + height, radius)
  ctx.arcTo(x, y + height, x, y, radius)
  ctx.arcTo(x, y, x + width, y, radius)
  ctx.closePath()
}

Conclusion

Arc(the arcTo function) is better than QuadraticCurve in canvas border-radius implement.
You can use the function to crop images in RoundedRectangle shape, and this is what the RRcrop (opens in a new tab) doing.