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.
CodePudding user response:
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;
}