Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...

GreenSock Docs

snap()

Returns : *

Returns the closest number (or object of x and y coordinates) to the number that you give it. Or returns a function that returns those things.


Snap to a certain increment or to the closest value in an array. You can even limit snapping to when the provided value is within a certain radius/distance of one of those in the array. This even works with 2-dimensional points (objects with x and y properties) and it factors both dimensions into the radius measurement. Note that if you don’t provide a value to snap (the 2nd parameter), gsap.utils.snap() returns a function that you can feed any number and it’ll perform the snapping accordingly.

  1. //declare a snapping increment of 10, and snap 23.5 accordingly
  2. let num = gsap.utils.snap(10, 23.5); //20
  3. //or snap to the closest value in an array:
  4. let num = gsap.utils.snap([0, 10, 30], 23.5); //30
  5. //or define a radius so that snapping only occurs when the provided value is within that radius of one of the values in the array:
  6. let num = gsap.utils.snap({values:[0, 100, 300], radius:20}, 30.5); //30.5 (because it's not within the radius)
  7. //also works with points (objects with "x" and "y" properties):
  8. let point = {x:8, y:8};
  9. let snappedPoint = gsap.utils.snap({values:[{x:0, y:0}, {x:10, y:10}, {x:20, y:20}], radius:5}, point); //{x:10, y:10}
  10. //if we don't provide a value to snap, we'll get a function back that's ready to perform snapping accordingly:
  11. let snapper = gsap.utils.snap([0, 100, 500]); // <- function!
  12. //now whatever value we feed that resulting function (from the line above) will be snapped accordingly:
  13. let num = snapper(80); // 100
Copyright 2017, GreenSock. All rights reserved. This work is subject to theterms of useor for Club GreenSock members, the software agreement that was issued with the membership.
×