计算点是否位于虚线上或间隙上的公式
我正在寻找一个公式来检查任意长度的虚线上的点是否落在破折号或间隙上。
我的方法是使用以下公式,
/**
* @param t The point to check
* @param dash The length of a dash
* @param gap The length of a gap
*/
function isOnDash(t, dash, gap) {
const verticalOffset = 1 - gap / (dash + gap);
const period = (2 * Math.PI) / (dash + gap);
const phase = Math.asin(-verticalOffset) / period;
return Math.sin(period * (t + phase)) + verticalOffset >= 0;
}
这几乎可行,但不是 100% 准确。这里是一个 JSFiddle ,它展示了这种方法与在 HTML 画布元素上绘制虚线的比较。
I'm looking for a formula to check if a point on a dashed line of any length either falls onto a dash or gap.
My approach is to use the following formula
/**
* @param t The point to check
* @param dash The length of a dash
* @param gap The length of a gap
*/
function isOnDash(t, dash, gap) {
const verticalOffset = 1 - gap / (dash + gap);
const period = (2 * Math.PI) / (dash + gap);
const phase = Math.asin(-verticalOffset) / period;
return Math.sin(period * (t + phase)) + verticalOffset >= 0;
}
This nearly works, but it's not 100% accurate. Here is a JSFiddle that shows this approach in comparison to a drawing a dashed line on a HTML canvas element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个算术问题,而不是一个连续数的问题。应尽可能避免使用浮点和 Math.sin 或浮点除法等函数,这将不可避免地导致近似错误。
相反,取模是对您的问题的简单算术答案。
This is an arithmetic problem, not a problem with continuous numbers. As much as possible, you should avoid floating-points and functions like Math.sin or floating-point division, which will unavoidably result in approximation errors.
Instead, modulo is a simple arithmetic answer to your problem.