svg绘制2点之间的虚线钟形曲线

时间:2016-09-14 07:54:43

标签: javascript svg

我想用svg绘制一条钟形曲线,如下图所示。所以基本上我应该能够传递3个参数:x1,x2和高度,它应绘制一个虚线的钟形曲线。实现这一目标的最佳方法是什么?

enter image description here

这是我绘制常规贝塞尔曲线的方法。基本上我需要弄清楚如何将它转换为钟形曲线:

function getDimension(x1, x2, height) {
  return "M" + x1 + "," + height + " C" + x1 + ",0 " + x2 + ",0 " + x2 + "," + height;
}

var curve = document.createElementNS("http://www.w3.org/2000/svg", "path");
curve.setAttribute("d", getDimension(0, 100, 50));
curve.setAttribute("x", '0');
curve.setAttribute("fill", 'none');
curve.setAttribute("stroke", 'black');
curve.setAttribute("stroke-dasharray", '5');
document.getElementById('svg').appendChild(curve);

enter image description here

1 个答案:

答案 0 :(得分:5)

您可以使用三次曲线来获得近似钟形的曲线。使用SVG中的C绘制立方曲线:



function bellCurve(x1, x2, height)
{
    var width = x2-x1;
    var quart = width/4;
  
    return `M0 ${height} C ${quart} ${height}, ${quart} 0, ${quart*2} 0, ${quart*3} 0, ${quart*3} ${height}, ${quart*4} ${height}`;
}

var curve = document.createElementNS("http://www.w3.org/2000/svg", "path");
curve.setAttribute("d", bellCurve(0, 100, 50));
curve.setAttribute("x", '0');
curve.setAttribute("fill", 'none');
curve.setAttribute("stroke", 'black');
curve.setAttribute("stroke-dasharray", '5');
document.getElementById('svg').appendChild(curve);

<svg id="svg" />
&#13;
&#13;
&#13;

您可能希望移动/添加手柄以更准确地匹配钟形曲线。在需要时,模板文字也可以用字符串连接替换。