Skip to content

Instantly share code, notes, and snippets.

@aPinix
Last active April 16, 2024 21:22
Show Gist options
  • Select an option

  • Save aPinix/708391fe11f50574494e041e8608e22c to your computer and use it in GitHub Desktop.

Select an option

Save aPinix/708391fe11f50574494e041e8608e22c to your computer and use it in GitHub Desktop.
Create a rounded rectangle (different radius for each corner)
createRoundRect('.wrapper', 0, 0, 400, 300, 40, 70, 20, 110);
/**
* Create a rounded rectangle (allows for different radius on each corner)
* @param {String} selector The selector for the element to append to
* @param {Number} positionX Position of the rectangle on the x axis
* @param {Number} positionY Position of the rectangle on the y axis
* @param {Number} width Width of the rectangle
* @param {Number} height Height of the rectangle
* @param {Number} topLeftRadius Radius of the top left corner
* @param {Number} topRightRadius Radius of the top right corner
* @param {Number} bottomRightRadius Radius of the bottom right corner
* @param {Number} bottomLeftRadius Radius of the bottom left corner
*/
function createSvgRectWithBorderRadius(selector, positionX, positionY, width, height, topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius) {
const svgRectWithBorderRadius = (positionX, positionY, width, height, topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius) => {
return `M${positionX + topLeftRadius},${positionY}\
h${width - (topLeftRadius + topRightRadius)}\
a${topRightRadius},${topRightRadius} 0 0 1 ${topRightRadius},${topRightRadius}\
v${height - (topRightRadius + bottomRightRadius)}\
a${bottomRightRadius},${bottomRightRadius} 0 0 1 -${bottomRightRadius},${bottomRightRadius}\
h-${width - (bottomLeftRadius + bottomRightRadius)}\
a${bottomLeftRadius},${bottomLeftRadius} 0 0 1 -${bottomLeftRadius},-${bottomLeftRadius}\
v-${height - (topLeftRadius + bottomLeftRadius)}\
a${topLeftRadius},${topLeftRadius} 0 0 1 ${topLeftRadius},-${topLeftRadius}\
z`;
}
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', width);
svg.setAttribute('height', height);
document.querySelector(selector).append(svg);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', svgRectWithBorderRadius(positionX, positionY, width, height, topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius));
svg.append(path);
}
@aPinix
Copy link
Author

aPinix commented Aug 25, 2022

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