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)

createSvgRectWithBorderRadius('.wrapper', '#09f', 0, 0, 400, 300, 40, 70, 20, 110);

/**

  • Create a rounded rectangle (allows for different radius on each corner)
  • @author aPinix https://twitter.com/aPinix
  • @version 1.0
  • @see {@link https://codepen.io/aPinix/pen/dyRvjQq}
  • @link https://codepen.io/aPinix/pen/dyRvjQq
  • @param {string} elemSelector The selector for the element to append the svg
  • @param {string} color The color of the rectangle
  • @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(elemSelector, color, 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(elemSelector).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)); path.setAttribute('fill', color); 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