答案 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;