roundRect.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * https://stackoverflow.com/a/3368118
  3. * Draws a rounded rectangle using the current state of the canvas.
  4. * @param {CanvasRenderingContext2D} context
  5. * @param {Number} x The top left x coordinate
  6. * @param {Number} y The top left y coordinate
  7. * @param {Number} width The width of the rectangle
  8. * @param {Number} height The height of the rectangle
  9. * @param {Number} radius The corner radius
  10. */
  11. export const roundRect = (
  12. context: CanvasRenderingContext2D,
  13. x: number,
  14. y: number,
  15. width: number,
  16. height: number,
  17. radius: number,
  18. ) => {
  19. context.beginPath();
  20. context.moveTo(x + radius, y);
  21. context.lineTo(x + width - radius, y);
  22. context.quadraticCurveTo(x + width, y, x + width, y + radius);
  23. context.lineTo(x + width, y + height - radius);
  24. context.quadraticCurveTo(
  25. x + width,
  26. y + height,
  27. x + width - radius,
  28. y + height,
  29. );
  30. context.lineTo(x + radius, y + height);
  31. context.quadraticCurveTo(x, y + height, x, y + height - radius);
  32. context.lineTo(x, y + radius);
  33. context.quadraticCurveTo(x, y, x + radius, y);
  34. context.closePath();
  35. context.fill();
  36. context.stroke();
  37. };