admin管理员组

文章数量:1317909

I would like to draw a bell curve, that looks like the image below, with svg. So essentially I should be able to pass 3 parameters: x1, x2, and height and it should draw a dashed bell curve. What is the best way to achieve this?

Here is what I have for drawing a regular bezier curve. Basically I need to figure out how to convert it to a bell curve:

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

var curve = document.createElementNS("", "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);

I would like to draw a bell curve, that looks like the image below, with svg. So essentially I should be able to pass 3 parameters: x1, x2, and height and it should draw a dashed bell curve. What is the best way to achieve this?

Here is what I have for drawing a regular bezier curve. Basically I need to figure out how to convert it to a bell curve:

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

var curve = document.createElementNS("http://www.w3/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);

Share Improve this question edited Sep 14, 2016 at 9:10 Marin Petkov asked Sep 14, 2016 at 7:54 Marin PetkovMarin Petkov 2,1584 gold badges17 silver badges23 bronze badges 1
  • Why downvote before asking me to provide info? I updated the description to show where I am so far. – Marin Petkov Commented Sep 14, 2016 at 9:10
Add a ment  | 

1 Answer 1

Reset to default 12

You can use a cubic curve to get a curve that approximates a bell. Cubic curves are drawn using C in SVG:

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/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" />

You may want to move/add handles to match the bell curve more correctly. Also template literals may be replaced with string concatenation when required.

本文标签: javascriptsvg draw dashed bell curve between 2 pointsStack Overflow