Skip to content

Instantly share code, notes, and snippets.

@hu9o
Created October 6, 2016 13:10
Show Gist options
  • Save hu9o/cf7d4bd40c486cb4b9443a52916bc226 to your computer and use it in GitHub Desktop.
Save hu9o/cf7d4bd40c486cb4b9443a52916bc226 to your computer and use it in GitHub Desktop.
Draws a rectangle with rounded corners on a canvas.
function drawRoundedRect(context, x, y, width, height, borderRadius) {
if (!borderRadius) {
context.rect(x, y, width, height);
} else {
var widthMinusRad = width - borderRadius;
var heightMinusRad = height - borderRadius;
context.translate(x, y);
context.arc(borderRadius, borderRadius, borderRadius, Math.PI, Math.PI * 1.5);
context.lineTo(widthMinusRad, 0);
context.arc(widthMinusRad, borderRadius, borderRadius, Math.PI * 1.5, Math.PI * 2);
context.lineTo(width, heightMinusRad);
context.arc(widthMinusRad, heightMinusRad, borderRadius, Math.PI * 2, Math.PI * 0.5);
context.lineTo(borderRadius, height);
context.arc(borderRadius, heightMinusRad, borderRadius, Math.PI * 0.5, Math.PI);
context.translate(-x, -y);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment