Bharathi
Bharathi

Reputation: 1328

How to draw a rounded corner in rectangle's bottom svg JS

I want to draw a rectangle with rounded corner only on the bottom of the place without using external source using HTML5 SVG element. Any one can help on this?. I have attached the expected output.

enter image description here

Thanks, Bharathi

Upvotes: 2

Views: 1035

Answers (1)

Andrew Willems
Andrew Willems

Reputation: 12458

Below is a function entitled makeShape that draws the desired shape. The input parameters are x (i.e. left), y (i.e. top), width, height and r (i.e. corner radius). It returns an svg path element.

To learn more you can consult this general reference for SVG, as well as specific information about how to create a path.

The demo below creates shapes with random positions and dimensions, including random corner radii. Comments in the code explain how this is done.

// the shape creation function
var makeShape = function(x, y, width, height, r) {
  var xmlns = "http://www.w3.org/2000/svg";
  var
    spc         = " ", // path drawing instruction letters with readable names
    moveTo      = "M",
    horizLineTo = "h",
    vertLineTo  = "v",
    arcTo       = "a",
    closePath   = "z";
  var dStr = // the "d" path for the svg path
    moveTo      + spc + x + spc + y + spc +
    vertLineTo  + spc + (height - r) + spc +
    arcTo       + spc + r + spc + r + spc + 0 + spc + 0 + spc + 0 + spc + r + spc + r + spc +
    horizLineTo + spc + (width - 2 * r) + spc +
    arcTo       + spc + r + spc + r + spc + 0 + spc + 0 + spc + 0 + spc + r + spc + (-r) + spc +
    vertLineTo  + spc + (r - height) + spc +
    closePath;
  var shape = document.createElementNS(xmlns, "path"); // create the (orphan) svg path element
  shape.setAttribute("d", dStr); // add the "d" attribute to the path, giving it a shape
  return shape; // return it from the function
};

// demo code for creating randomly positioned and proportioned example shapes
document.querySelector("button").addEventListener("click", function() {
  var path = document.querySelector("path"); // if any previous paths exist, delete them
  if (path) {path.parentNode.removeChild(path);}
  var x = Math.random() * 140 + 10; // calculate random location and proportions for the shape
  var y = Math.random() * 65 + 10;
  var width  = 400 - x * 2;
  var height = 150 - y * 2;
  var r = Math.random() * Math.min(width / 2, height); // the corner radius
  var shape = makeShape(x, y, width, height, r); // create the orphan shape
  shape.setAttribute("stroke", "grey"); // style its appearance
  shape.setAttribute("fill", "red");
  shape.setAttribute("stroke-width", "4");
  document.querySelector("svg").appendChild(shape); // add the shape to the SVG DOM
});
<svg width="400" height="150"></svg>
<div><button>Draw random shape</button></div>

Upvotes: 4

Related Questions