Created
August 4, 2021 15:18
-
-
Save Hirosaji/bb74210155691a01c62af9a1cdc53fac to your computer and use it in GitHub Desktop.
ScrollyTelling with FreeCamera API snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
// 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