计算点是否位于虚线上或间隙上的公式

发布于 2025-01-12 03:21:15 字数 626 浏览 1 评论 0原文

我正在寻找一个公式来检查任意长度的虚线上的点是否落在破折号或间隙上。

我的方法是使用以下公式,

/**
 * @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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单 2025-01-19 03:21:16

这是一个算术问题,而不是一个连续数的问题。应尽可能避免使用浮点和 Math.sin 或浮点除法等函数,这将不可避免地导致近似错误。

相反,取模是对您的问题的简单算术答案。

/**
 * @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) {
  return (t % (dash + gap)) < dash;
}

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.

/**
 * @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) {
  return (t % (dash + gap)) < dash;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文