Search code examples
javascriptmathcurvelogarithm

Numbers that result in a more rounded corner when graphing in Javascript


I have a for loop that returns a decimal between 0 and 1. I'd like to make a curve that appears more like a rounded corner than it is now. I'd also like to have it start ramping up only after 0.25. I can't quite figure out how to do it with the math I have now. I'm using Math.log and a linear conversion function, but maybe I need something more related to a parabolic curve.

for (i = 1; i < 101; ++i) {
  var dec = i / 100
  if (dec >= 0.25) {
    console.log("dec = " + dec);
    var large = i * 100
    var log = Math.log(large);
    console.log("log = " + log);
    var linCon = applyLinearConversion(log, 2.8, 9.2104, -2.7, 1)
    console.log("linCon " + i + " = " + linCon);
    document.getElementById("graph").innerHTML += "<div style='background-color:#000000; width:" + (linCon * 1000) + "px; height:5px;'></div>";
  }
}

function applyLinearConversion(OldValue, OldMin, OldMax, NewMin, NewMax) {
  OldRange = (OldMax - OldMin)
  if (OldRange == 0)
    NewValue = NewMin
  else {
    NewRange = (NewMax - NewMin)
    NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
  }

  return NewValue

}
<div id="graph"></div>

I have it populating a div with more styled divs.

Mine is like this: enter image description here

I want mine more like this: enter image description here


Solution

  • You can use the formula of the half circle graph which is:

    It results in the following graph:

    Since you are using horizontal divs that are stacked vertically to draw the graph, the x and y coordinates will be reversed and the left quarter of the circle will be used from the above graph.

    var width = 200;                             // the width of the graph
    var height = 200;                            // the height of the graph
    var xOffset = 0.25 * width;                  // the x offset at which the graph will start ramping up (this offset is added to the graph width)
    
    var html = "";                               // to accumulate the generated html before assigning it to innerHTML (it's not a good idea to constantly update innerHTML)
    
    for (i = 1; i < 101; ++i) {
      var x = 1 - i / 100;                       // the x coordinate, we are using the left side of the graph so x should be negative going from -1 to 0
      var y = Math.sqrt(1 - x * x);              // the y coordinate as per the formula (this will be used for the width)
      html += "<div style='background-color:#000000; width:" + (xOffset + y * width) + "px; height:" + (height / 100) + "px;'></div>";
    }
    
    document.getElementById("graph").innerHTML = html;
    <div id="graph"></div>