Skip to content

Instantly share code, notes, and snippets.

@jose-mdz
Created October 13, 2022 18:26
Show Gist options
  • Save jose-mdz/1156eeae0a8d21a561d96c917579be59 to your computer and use it in GitHub Desktop.
Save jose-mdz/1156eeae0a8d21a561d96c917579be59 to your computer and use it in GitHub Desktop.
Rounded Rectangle
export function roundRect(
context: CanvasRenderingContext2D,
rectangle: Rectangle,
radius: number | {tl?: number, tr?: number, br?: number, bl?: number} = 5,
fill: boolean,
stroke = false,
) {
const [x, y, width, height] = rectangle.tuple;
const rad = typeof radius === 'number' ?
{tl: radius, tr: radius, br: radius, bl: radius} :
{...{tl: 0, tr: 0, br: 0, bl: 0}, ...radius};
context.beginPath();
context.moveTo(x + rad.tl, y);
context.lineTo(x + width - rad.tr, y);
context.quadraticCurveTo(x + width, y, x + width, y + rad.tr);
context.lineTo(x + width, y + height - rad.br);
context.quadraticCurveTo(x + width, y + height, x + width - rad.br, y + height);
context.lineTo(x + rad.bl, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - rad.bl);
context.lineTo(x, y + rad.tl);
context.quadraticCurveTo(x, y, x + rad.tl, y);
context.closePath();
if (fill) {
context.fill();
}
if (stroke) {
context.stroke();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment