首页 > 解决方案 > 在 Javascript 中绘图时导致更圆角的数字

问题描述

我有一个 for 循环,它返回 0 到 1 之间的小数。我想做一条看起来比现在更像圆角的曲线。我也想让它在 0.25 之后才开始加速。我无法完全弄清楚如何用我现在的数学来做到这一点。我正在使用 Math.log 和线性转换函数,但也许我需要与抛物线曲线更相关的东西。

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>

我让它用更多样式的 div 填充一个 div。

我的是这样的: 在此处输入图像描述

我想要我的更像这样: 在此处输入图像描述

标签: javascriptmathcurvelogarithm

解决方案


您可以使用半圆图的公式,即:

结果如下图:

由于您使用垂直堆叠的水平 div 来绘制图形,因此 x 和 y 坐标将反转,并且将使用上图中的左四分之一圆。

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>


推荐阅读