Created
January 8, 2013 15:07
-
-
Save afreeland/4484489 to your computer and use it in GitHub Desktop.
JavaScript: Create rounded rectangle HTML5 Canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
/** | |
* [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(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
May you please explain how this works?