Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hirosaji/bb74210155691a01c62af9a1cdc53fac to your computer and use it in GitHub Desktop.
Save Hirosaji/bb74210155691a01c62af9a1cdc53fac to your computer and use it in GitHub Desktop.
ScrollyTelling with FreeCamera API snippet
...
// get the overall length of each route so we can interpolate along them
const routeLength = turf.length(turf.lineString(targetRoute));
const cameraRouteLength = turf.length(turf.lineString(targetRoute));
function frame() {
...
// use the rate to get a point that is the appropriate length along the route
// this approach syncs the camera and route positions ensuring they move
// at roughly equal rates even if they don't contain the same number of points
const alongRoute = turf.along(
turf.lineString(shortTargetRoute),
routeLength * rate
).geometry.coordinates;
const alongCamera = turf.along(
turf.lineString(cameraRoute),
cameraRouteLength * rate
).geometry.coordinates;
const camera = map.getFreeCameraOptions();
// set the position and altitude of the camera
camera.position = mapboxgl.MercatorCoordinate.fromLngLat(
{
lng: alongCamera[0],
lat: alongCamera[1]
},
cameraAltitude
);
// tell the camera to look at a point along the route
camera.lookAtPoint({
lng: alongRoute[0],
lat: alongRoute[1]
});
map.setFreeCameraOptions(camera);
}
let ticking = false;
function scrollEvent() {
if (!ticking) {
requestAnimationFrame(frame);
ticking = true;
}
}
document.addEventListener('scroll', scrollEvent, {passive: true});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment