【问题标题】:svg draw dashed bell curve between 2 pointssvg 在两点之间绘制虚线钟形曲线
【发布时间】:2016-09-14 07:54:43
【问题描述】:

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

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

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);

【问题讨论】:

  • 为什么在要求我提供信息之前投反对票?我更新了描述以显示我到目前为止的位置。

标签: javascript svg


【解决方案1】:

您可以使用三次曲线来获得近似钟形的曲线。在 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" />

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 2017-02-18
    • 2019-08-15
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多