I was having some trouble finding how to create a parallax based on scroll speed in two images on my nuxt 3 website. After some research and trial and error I succeededπ₯³. Maybe this will be useful to you π
Steps I followed:
1- Read this Nuxt GSAP module
2- Install the module
bun add -D @hypernym/nuxt-gsap
Use your preferred package manager. I'm using bun
3- Add the module in your nuxt.config.ts
// nuxt.config.ts
{
modules: ['@hypernym/nuxt-gsap']
}
4- Add this configs to your Nuxt GSAP Module
// nuxt.config.ts
gsap: {
composables: true,
provide: false,
},
5- In your app.vue register the ScrollTrigger
<script setup lang="ts">
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
onMounted(() => {
gsap.registerPlugin(ScrollTrigger)
})
</script>
6- In the file where you want to create a parallax image effect, import your GSAP and scrollTrigger in the script configuration
<script setup lang="ts">
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
</script>
7- Now Let's create the speed scroll parallax image effect
Contextualizing: The function animates elements with a data-speed attribute, making them move vertically as the user scrolls the page.
- Higher data-speed = less movement, creating a parallax effect where different elements move at different speeds relative to the scroll position.
Script:
<script setup lang="ts">
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
onMounted(() => {
gsap.to('[data-speed]', {
y: (i, el) => (1 - Number.parseFloat(el.getAttribute('data-speed'))) * ScrollTrigger.maxScroll(window),
ease: 'none',
scrollTrigger: {
start: 0,
end: 'max',
invalidateOnRefresh: true,
scrub: 0,
},
})
})
</script>
Template
<template>
<section>
<NuxtImg
data-speed="0.9"
class="absolute top-50 w-15 -right-6"
src="my-path.webp"
/>
<NuxtImg
data-speed="0.8"
class="absolute top-50 w-15 -right-6"
src="my-path.webp"
/>
</section>
</template>
PS.: Check out my reference π
Hope this helps! :)
Top comments (0)