如何在矩形的底部svg JS

时间:2016-03-02 09:52:53

标签: javascript jquery html html5 svg

我想在地方底部绘制一个圆角的矩形,而不使用HTML5 SVG元素使用外部源。任何人都可以帮忙吗?我附上了预期的输出。

enter image description here

谢谢, Bharathi

1 个答案:

答案 0 :(得分:3)

下面是一个标题为makeShape的函数,它绘制了所需的形状。输入参数是x(即左),y(即顶部),宽度,高度和r(即角半径)。它返回一个svg路径元素。

要了解详情,您可以咨询this general reference for SVG,以及有关how to create a path的具体信息。

下面的演示创建了具有随机位置和尺寸的形状,包括随机角半径。代码中的注释解释了这是如何完成的。



// 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>
&#13;
&#13;
&#13;