javascript - 如何将像素距离转换为步长
问题描述
我想根据容器宽度和线相对于容器的距离来计算步数。
我能够计算步数,但只有最小步长为 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 );
步骤计算应返回的静态值的一些示例:
最终目标是能够用动态值计算步长......
- 如果线距离为
0
,则step
返回100
- 如果线距离为
10
,则step
返回105
- 如果线距离为
352
,则step
返回300
- 352是最大距离的一半
- 300 最小步数和最大步数之间的中间点
- 如果线距离为
704
,则step
返回500
解决方案
如果我理解正确,您只需要插入到步骤的距离,那么您需要先找到两个间隔的长度:
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;
推荐阅读
- azure - 使用 azure api 确定 azure 订阅中资源的价格
- android - 无法使用指南删除边距
- redis - Celery - 自动重试在崩溃的工作人员上运行的长时间运行的任务
- python - 电报机器人在命令 Python 后等待用户回复
- html - 矩形边框的CSS形状半圆对齐问题
- android - 请求 Google 驱动器范围权限时会提供无限加载对话框
- windows - 在支持 GPU 的 Windows 10 上部署 TF2 模型
- html - HTML 实体在页面刷新时未呈现正确的字符
- android - Android MVVM:当来自网络的数据没有改变时如何避免多个livedata触发器
- javascript - 正则表达式:搜索特殊字符并删除所有空格+易碎字符