You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * Get balanced dash-strokearray and dash-strokeoffset properties for a path of a given length.
  3. * @param length The length of the path.
  4. * @param strokeWidth The shape's stroke-width property.
  5. * @param style The stroke's style: "dashed" or "dotted" (default "dashed").
  6. * @param snap An interval for dashes (e.g. 4 will produce arrays with 4, 8, 16, etc dashes).
  7. */
  8. export function getPerfectDashProps(
  9. length: number,
  10. strokeWidth: number,
  11. style: 'dashed' | 'dotted' = 'dashed',
  12. snap = 1
  13. ): {
  14. strokeDasharray: string
  15. strokeDashoffset: string
  16. } {
  17. let dashLength: number
  18. let strokeDashoffset: string
  19. let ratio: number
  20. if (style === 'dashed') {
  21. dashLength = strokeWidth * 2
  22. ratio = 1
  23. strokeDashoffset = (dashLength / 2).toString()
  24. } else {
  25. dashLength = strokeWidth / 4
  26. ratio = 4
  27. strokeDashoffset = '0'
  28. }
  29. let dashes = Math.floor(length / dashLength / (2 * ratio))
  30. dashes -= dashes % snap
  31. if (dashes === 0) dashes = 1
  32. const gapLength = (length - dashes * dashLength) / dashes
  33. return {
  34. strokeDasharray: [dashLength, gapLength].join(' '),
  35. strokeDashoffset,
  36. }
  37. }