首页 > 解决方案 > 如何将像素距离转换为步长

问题描述

在此处输入图像描述

我想根据容器宽度和线相对于容器的距离来计算步数。

我能够计算步数,但只有最小步长为 0。但是,在我的场景中,最小步长可以大于 0,到目前为止我还无法弄清楚如何在计算中烘焙它.

检查此codepen中的完整示例。

// Small example:
// In this code, line distance 0 corresponds to step 0, but I want it to 
// correspond to step 100, since that is supposed to be the minimum step. 

var lineDistance = 0; // px
var maxDistance = 704; // px
var minSteps = 100; //step
var maxSteps = 500; //step
var step = Math.floor( (lineDistance/maxDistance) * maxSteps );

步骤计算应返回的静态值的一些示例:

最终目标是能够用动态值计算步长......

标签: javascript

解决方案


如果我理解正确,您只需要插入到步骤的距离,那么您需要先找到两个间隔的长度:

const distanceLength = maxLength - minLength; // probably maxLength - 0 in your case
const stepLength = maxSteps - minSteps;

然后标准化您的值(查找距离差异):

const distanceDiff = lineDistance - minDistance; // probably just lineDistance in your case

然后将其转换为绝对单位:

const distanceRate = distanceDiff / distanceLength;

然后转换成步骤:

const stepsDiff = distanceRate * stepsLength;

并以步长最小值移动:

const steps = minSteps + stepsDiff;

推荐阅读