Skip to content

Instantly share code, notes, and snippets.

@afreeland
Created January 8, 2013 15:07
Show Gist options
  • Save afreeland/4484489 to your computer and use it in GitHub Desktop.
Save afreeland/4484489 to your computer and use it in GitHub Desktop.
JavaScript: Create rounded rectangle HTML5 Canvas
{
/**
* [roundedRect description]
* @param {Canvas Context} ctx Canvas Context
* @param {int} x X Coordinate
* @param {int} y Y Coordinate
* @param {int} width Width of rectangle
* @param {int} height Height of rectangle
* @param {radius} radius Radius of rectangle corners
* @param {string} fill Any string of rgb or hex
* @param {string} stroke Color of stroke --if stroke === 0 it will not use default stroke
* @param {int} lineWidth The line width
* @return {[type]} [description]
*/
roundedRect: function (ctx, x, y, width, height, radius, fill, stroke, lineWidth) {
var useStroke = typeof stroke == 'undefined' || stroke !== 0;
radius = typeof radius == 'undefined' ? 5 : radius;
// Save previous context
ctx.save();
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();
if (useStroke && stroke !== 0) {
ctx.strokeStyle = typeof stroke == 'undefined' ? '#000' : stroke;
ctx.stroke();
}
if (fill) {
ctx.fillStyle = fill;
ctx.fill();
}
// Restore original context
ctx.restore();
}
};
@Goryn3l
Copy link

Goryn3l commented Mar 19, 2019

May you please explain how this works?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment