Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

svg draw dashed bell curve between 2 points

Tags:

javascript

svg

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?

enter image description here

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.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

like image 655
Marin Petkov Avatar asked Sep 14 '16 07:09

Marin Petkov


1 Answers

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

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.

like image 161
Caramiriel Avatar answered Oct 22 '22 14:10

Caramiriel