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.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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With