Codrops 원본
How to Animate WebGL Shaders with GSAP: Ripples, Reveals, and Dynamic Blur Effects
배경 · MIT
갤러리 안에서는 화면을 벗어나거나 움직임을 멈추면 예제도 닫힙니다. 다시 재생할 때는 처음부터 시작해요.
SOURCE FILES
원본 코드 읽기
수집한 원본 소스와 실행 안내를 함께 제공합니다.
index.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Animating Shaders with GSAP | Demo 1 | Codrops</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="https://tympanus.net/favicon/favicon.ico" />
<link rel="stylesheet" type="text/css" href="./src/css/reset.css" />
<link rel="stylesheet" type="text/css" href="./src/css/base.css" />
<script>
document.documentElement.className = 'js';
</script>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<!--script src=".//tympanus.net/codrops/adpacks/analytics.js"></script-->
</head>
<body class="demo-1 loading">
<main>
<header class="frame">
<nav class="frame__tags">
<a href="https://tympanus.net/codrops/demos/?tag=gsap">#GSAP</a>
<a href="https://tympanus.net/codrops/demos/?tag=three-js">#THREE.JS</a>
<a href="https://tympanus.net/codrops/demos/?tag=webgl">#WEBGL</a>
</nav>
<div class="frame__center">
<h1 class="frame__title">Animating Shaders with GSAP</h1>
<nav class="frame__nav">
(Variation ⎯
<span class="active">01</span>
<span class="frame__nav-sep">.</span>
<a href="./index2.html">02</a>
<span class="frame__nav-sep">.</span>
<a href="./index3.html">03</a>
<span class="frame__nav-sep">.</span>
<a href="./index4.html">04</a>
)
</nav>
<p class="frame__description">Click on an image to see the effect</p>
</div>
</header>
<section class="content">
<div class="content__carousel">
<div class="content__carousel-inner-static">
<div class="content__carousel-image">
<img src="./images/06.webp" alt="" role="presentation" />
<span>Pose — 001</span>
</div>
<div class="content__carousel-image">
<img src="./images/07.webp" alt="" role="presentation" />
<span>Stand — 002</span>
</div>
<div class="content__carousel-image">
<img src="./images/08.webp" alt="" role="presentation" />
<span>Dance — 003</span>
</div>
<div class="content__carousel-image">
<img src="./images/09.webp" alt="" role="presentation" />
<span>Attitude — 004</span>
</div>
</div>
</div>
</section>
<div class="floating-bar">
<a class="floating-bar__link floating-bar__link-back" href="https://tympanus.net/codrops/?p=102374">Article</a>
<a class="floating-bar__link floating-bar__link-archive" href="https://tympanus.net/codrops/demos/">
All Demos
</a>
<a
class="floating-bar__link floating-bar__link-github"
href="https://github.com/biazo/codrops-animate-shaders-with-gsap"
>
GitHub
</a>
</div>
</main>
<script src="https://tympanus.net/codrops/adpacks/cda_sponsor.js"></script>
<script src="./src/js/libs/imagesloaded.pkgd.min.js" type="module"></script>
<script type="module" src="./src/js/demo1/main.js"></script>
</body>
</html>
index2.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Animating Shaders with GSAP | Demo 2 | Codrops</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="https://tympanus.net/favicon/favicon.ico" />
<link rel="stylesheet" type="text/css" href="./src/css/reset.css" />
<link rel="stylesheet" type="text/css" href="./src/css/base.css" />
<script>
document.documentElement.className = 'js';
</script>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<!--script src=".//tympanus.net/codrops/adpacks/analytics.js"></script-->
</head>
<body class="demo-2 loading">
<main>
<header class="frame">
<nav class="frame__tags">
<a href="https://tympanus.net/codrops/demos/?tag=gsap">#GSAP</a>
<a href="https://tympanus.net/codrops/demos/?tag=three-js">#THREE.JS</a>
<a href="https://tympanus.net/codrops/demos/?tag=webgl">#WEBGL</a>
</nav>
<div class="frame__center">
<h1 class="frame__title">Animating Shaders with GSAP</h1>
<nav class="frame__nav">
(Variation ⎯
<a href="./index.html">01</a>
<span class="frame__nav-sep">.</span>
<span class="active">02</span>
<span class="frame__nav-sep">.</span>
<a href="./index3.html">03</a>
<span class="frame__nav-sep">.</span>
<a href="./index4.html">04</a>
)
</nav>
<p class="frame__description">Hover an image to see the effect</p>
</div>
</header>
<section class="content">
<div class="content__carousel">
<div class="content__carousel-inner-static">
<div class="content__carousel-image">
<img src="./images/01.webp" alt="" role="presentation" data-back="./images/01_x.webp" />
<span>Nephra — 001</span>
</div>
<div class="content__carousel-image">
<img src="./images/02.webp" alt="" role="presentation" data-back="./images/02_x.webp" />
<span>Orryx — 002</span>
</div>
<div class="content__carousel-image">
<img src="./images/03.webp" alt="" role="presentation" data-back="./images/03_x.webp" />
<span>Velith — 003</span>
</div>
<div class="content__carousel-image">
<img src="./images/04.webp" alt="" role="presentation" data-back="./images/04_x.webp" />
<span>Kaelun — 004</span>
</div>
</div>
</div>
</section>
<div class="floating-bar">
<a class="floating-bar__link floating-bar__link-back" href="https://tympanus.net/codrops/?p=102374">Article</a>
<a class="floating-bar__link floating-bar__link-archive" href="https://tympanus.net/codrops/demos/">
All Demos
</a>
<a
class="floating-bar__link floating-bar__link-github"
href="https://github.com/biazo/codrops-animate-shaders-with-gsap"
>
GitHub
</a>
</div>
</main>
<script src="https://tympanus.net/codrops/adpacks/cda_sponsor.js"></script>
<script src="./src/js/libs/imagesloaded.pkgd.min.js" type="module"></script>
<script type="module" src="./src/js/demo2/main.js"></script>
</body>
</html>
함께 쓰는 파일 34개 보기
index3.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Animating Shaders with GSAP | Demo 3 | Codrops</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="https://tympanus.net/favicon/favicon.ico" />
<link rel="stylesheet" type="text/css" href="./src/css/reset.css" />
<link rel="stylesheet" type="text/css" href="./src/css/base.css" />
<script>
document.documentElement.className = 'js';
</script>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<!--script src=".//tympanus.net/codrops/adpacks/analytics.js"></script-->
</head>
<body class="demo-3 loading">
<main>
<header class="frame">
<nav class="frame__tags">
<a href="https://tympanus.net/codrops/demos/?tag=gsap">#GSAP</a>
<a href="https://tympanus.net/codrops/demos/?tag=three-js">#THREE.JS</a>
<a href="https://tympanus.net/codrops/demos/?tag=webgl">#WEBGL</a>
</nav>
<div class="frame__center">
<h1 class="frame__title">Animating Shaders with GSAP</h1>
<nav class="frame__nav">
(Variation ⎯
<a href="./index.html">01</a>
<span class="frame__nav-sep">.</span>
<a href="./index2.html">02</a>
<span class="frame__nav-sep">.</span>
<span class="active">03</span>
<span class="frame__nav-sep">.</span>
<a href="./index4.html">04</a>
)
</nav>
<p class="frame__description">Click and hold on an image to see the effect</p>
</div>
</header>
<section class="content">
<div class="content__carousel">
<div class="content__carousel-inner-static">
<div class="content__carousel-image">
<img src="./images/10.webp" alt="" role="presentation" />
<span>Rynal — 001</span>
</div>
<div class="content__carousel-image">
<img src="./images/11.webp" alt="" role="presentation" />
<span>Thalor — 002</span>
</div>
<div class="content__carousel-image">
<img src="./images/12.webp" alt="" role="presentation" />
<span>Iskari — 003</span>
</div>
<div class="content__carousel-image">
<img src="./images/13.webp" alt="" role="presentation" />
<span>Veyra — 004</span>
</div>
</div>
</div>
</section>
<div class="floating-bar">
<a class="floating-bar__link floating-bar__link-back" href="https://tympanus.net/codrops/?p=102374">Article</a>
<a class="floating-bar__link floating-bar__link-archive" href="https://tympanus.net/codrops/demos/">
All Demos
</a>
<a
class="floating-bar__link floating-bar__link-github"
href="https://github.com/biazo/codrops-animate-shaders-with-gsap"
>
GitHub
</a>
</div>
</main>
<script src="https://tympanus.net/codrops/adpacks/cda_sponsor.js"></script>
<script src="./src/js/libs/imagesloaded.pkgd.min.js" type="module"></script>
<script type="module" src="./src/js/demo3/main.js"></script>
</body>
</html>
index4.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Animating Shaders with GSAP | Demo 4 | Codrops</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="https://tympanus.net/favicon/favicon.ico" />
<link rel="stylesheet" type="text/css" href="./src/css/reset.css" />
<link rel="stylesheet" type="text/css" href="./src/css/base.css" />
<script>
document.documentElement.className = 'js';
</script>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<!--script src=".//tympanus.net/codrops/adpacks/analytics.js"></script-->
</head>
<body class="demo-4 loading">
<main>
<header class="frame">
<nav class="frame__tags">
<a href="https://tympanus.net/codrops/demos/?tag=gsap">#GSAP</a>
<a href="https://tympanus.net/codrops/demos/?tag=three-js">#THREE.JS</a>
<a href="https://tympanus.net/codrops/demos/?tag=webgl">#WEBGL</a>
</nav>
<div class="frame__center">
<h1 class="frame__title">Animating Shaders with GSAP</h1>
<nav class="frame__nav">
(Variation ⎯
<a href="./index.html">01</a>
<span class="frame__nav-sep">.</span>
<a href="./index2.html">02</a>
<span class="frame__nav-sep">.</span>
<a href="./index3.html">03</a>
<span class="frame__nav-sep">.</span>
<span class="active">04</span>
)
</nav>
<p class="frame__description">Scroll to see the effect</p>
</div>
</header>
<section class="content">
<div class="content__carousel">
<div class="content__carousel-inner centered">
<div class="content__carousel-image">
<img src="./images/14.webp" alt="" role="presentation" />
<span>Ether — 001</span>
</div>
<div class="content__carousel-image">
<img src="./images/15.webp" alt="" role="presentation" />
<span>Vapor — 002</span>
</div>
<div class="content__carousel-image">
<img src="./images/16.webp" alt="" role="presentation" />
<span>Halo — 003</span>
</div>
<div class="content__carousel-image">
<img src="./images/21.webp" alt="" role="presentation" />
<span>Pulse — 006</span>
</div>
<div class="content__carousel-image">
<img src="./images/17.webp" alt="" role="presentation" />
<span>Orion — 005</span>
</div>
<div class="content__carousel-image">
<img src="./images/18.webp" alt="" role="presentation" />
<span>Gleam — 006</span>
</div>
<div class="content__carousel-image">
<img src="./images/22.webp" alt="" role="presentation" />
<span>Mirth — 007</span>
</div>
<div class="content__carousel-image">
<img src="./images/23.webp" alt="" role="presentation" />
<span>Lucid — 008</span>
</div>
<div class="content__carousel-image">
<img src="./images/24.webp" alt="" role="presentation" />
<span>Flux — 009</span>
</div>
<div class="content__carousel-image">
<img src="./images/35.webp" alt="" role="presentation" />
<span>Astra — 010</span>
</div>
<div class="content__carousel-image">
<img src="./images/25.webp" alt="" role="presentation" />
<span>Veil — 011</span>
</div>
<div class="content__carousel-image">
<img src="./images/27.webp" alt="" role="presentation" />
<span>Dream — 012</span>
</div>
<div class="content__carousel-image">
<img src="./images/33.webp" alt="" role="presentation" />
<span>Lyra — 013</span>
</div>
<div class="content__carousel-image">
<img src="./images/29.webp" alt="" role="presentation" />
<span>Fable — 014</span>
</div>
<div class="content__carousel-image">
<img src="./images/30.webp" alt="" role="presentation" />
<span>Sol — 015</span>
</div>
<div class="content__carousel-image">
<img src="./images/32.webp" alt="" role="presentation" />
<span>Nova — 016</span>
</div>
</div>
</div>
</section>
<div class="floating-bar">
<a class="floating-bar__link floating-bar__link-back" href="https://tympanus.net/codrops/?p=102374">Article</a>
<a class="floating-bar__link floating-bar__link-archive" href="https://tympanus.net/codrops/demos/">
All Demos
</a>
<a
class="floating-bar__link floating-bar__link-github"
href="https://github.com/biazo/codrops-animate-shaders-with-gsap"
>
GitHub
</a>
</div>
</main>
<script src="https://tympanus.net/codrops/adpacks/cda_sponsor.js"></script>
<script src="./src/js/libs/imagesloaded.pkgd.min.js" type="module"></script>
<script type="module" src="./src/js/demo4/main.js"></script>
</body>
</html>
src/css/base.css
*,
*::after,
*::before {
box-sizing: border-box;
}
:root {
font-size: 12px;
--color-text: #000;
--color-bg: #fff;
--color-link: #000;
--color-gray: #959595;
--color-accent: #000000;
--color-link-hover: var(--color-accent);
--page-padding: 3vw;
--page-padding-vertical: 5vh;
}
html,
body {
overflow-x: hidden;
overflow-y: auto;
}
body {
margin: 0;
color: var(--color-text);
background-color: var(--color-bg);
font-family: 'Inter', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@media (scripting: enabled) {
.loading {
&::before,
&::after {
content: '';
position: fixed;
z-index: 10000;
}
&::before {
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--color-bg);
}
&::after {
top: 50%;
left: 50%;
width: 100px;
height: 1px;
margin: 0 0 0 -50px;
background: var(--color-link);
animation: loaderAnim 1.5s ease-in-out infinite alternate forwards;
}
}
}
@keyframes loaderAnim {
0% {
transform: scaleX(0);
transform-origin: 0% 50%;
}
50% {
transform: scaleX(1);
transform-origin: 0% 50%;
}
50.1% {
transform: scaleX(1);
transform-origin: 100% 50%;
}
100% {
transform: scaleX(0);
transform-origin: 100% 50%;
}
}
main {
overflow: hidden;
}
a {
text-decoration: none;
color: var(--color-link);
outline: none;
cursor: pointer;
&:hover {
/* text-decoration: underline; */
color: var(--color-link-hover);
}
&:focus {
outline: none;
background: lightgrey;
&:not(:focus-visible) {
background: transparent;
}
&:focus-visible {
outline: 2px solid red;
background: transparent;
}
}
}
.frame {
position: fixed;
top: 0;
left: 0;
width: 100vw;
display: grid;
grid-template-columns: 200px 1fr 200px;
justify-content: space-between;
padding: var(--page-padding-vertical) var(--page-padding);
z-index: 10;
@media (max-width: 767px) {
display: flex;
flex-direction: column;
position: relative;
align-items: center;
justify-content: center;
gap: 2rem;
}
.frame__title {
font-size: clamp(1.5rem, 2.5vw, 2.5rem);
font-weight: 600;
text-transform: uppercase;
letter-spacing: -0.1rem;
margin-bottom: 0.75rem;
@media (max-width: 767px) {
line-height: 1.15;
}
}
.frame__center {
text-align: center;
nav {
font-size: clamp(1.25rem, 1.75vw, 2rem);
color: var(--color-gray);
a {
color: var(--color-gray);
}
.active {
color: var(--color-accent);
}
}
}
.frame__description {
color: var(--color-text);
font-size: 1rem;
margin-top: 1rem;
@media (max-width: 767px) {
font-size: 12px;
margin-top: 20px;
}
}
.frame__sponsors {
justify-self: end;
}
.frame__tags,
.frame__sponsors {
display: flex;
flex-wrap: wrap;
gap: 1rem;
font-size: 1rem;
font-weight: 600;
padding-top: 1.2rem;
@media (max-width: 767px) {
padding-top: 0;
}
}
}
body #cdawrap {
grid-area: unset;
text-align: right;
@media (max-width: 767px) {
text-align: center;
}
}
.content {
width: 100vw;
height: 100svh;
position: relative;
display: flex;
align-items: center;
overflow: hidden;
.content__carousel {
position: absolute;
bottom: 8rem;
width: 100vw;
.content__carousel-inner {
width: fit-content;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 3rem;
padding-left: 45vw;
padding-right: 40vw;
img {
width: 30rem;
@media (max-width: 767px) {
width: 28rem;
}
}
}
.content__carousel-inner-static {
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 3rem;
padding-left: 3vw;
padding-right: 3vw;
@media (max-width: 767px) {
grid-template-rows: repeat(2, 1fr);
grid-template-columns: repeat(2, 1fr);
}
img {
width: 100%;
}
}
img {
opacity: 0;
margin-bottom: 1rem;
cursor: pointer;
}
span {
display: block;
}
}
.content__canvas {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100svh;
z-index: 2;
pointer-events: none;
}
}
.floating-bar {
position: fixed;
bottom: 2rem;
left: 50%;
transform: translateX(-50%);
display: grid;
grid-template-columns: repeat(3, 1fr);
align-items: center;
gap: 5px;
background-color: #d9d9d9;
border-radius: 8px;
padding: 4px;
z-index: 10;
.floating-bar__link {
padding: 7px 14px;
border-radius: 8px;
text-align: center;
font-size: 16px;
white-space: nowrap;
}
.floating-bar__link-back {
background-color: #000000;
color: #ffffff;
}
}
src/css/reset.css
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}src/js/demo1/Effect.js
import { gsap } from 'gsap';
import { Observer } from 'gsap/Observer';
import { Raycaster } from 'three';
export default class Effect {
constructor(scene, camera) {
this.scene = scene;
this.camera = camera;
this.activeObject = null;
// Initialize the Three.js raycaster for detecting object intersections
this.raycaster = new Raycaster();
// Set up GSAP Observer to listen for click or touch interactions
this.observer = Observer.create({
target: document.querySelector('.content__carousel'),
type: 'touch,pointer',
onClick: e => this.onClick(e),
});
}
animate(material, userData, mouseCoords) {
return gsap.timeline({
defaults: { duration: 1.5, ease: 'power3.inOut' },
// Update the uTime uniform continuously during the animation
onUpdate() {
material.uniforms.uTime.value += 0.1;
},
})
// Set mouse UV coordinates in the shader
.set(material.uniforms.uMouse, { value: mouseCoords }, 0)
// Set the direction of the grayscale effect (1 for BW, -1 for color)
.set(material.uniforms.uDirection, { value: userData.isBw ? 1.0 : -1.0 }, 0)
// Animate grayscale progress from 0 to 1
.fromTo(material.uniforms.uGrayscaleProgress, { value: 0 }, { value: 1 }, 0)
// Animate a ripple effect using a keyframe sequence [0 → 1 → 0]
.to(material.uniforms.uRippleProgress, { keyframes: { value: [0, 1, 0] } }, 0);
}
resetMaterial(object) {
// Reset all shader uniforms to default values
gsap.timeline({
defaults: { duration: 1, ease: 'power2.out' },
onUpdate() {
object.material.uniforms.uTime.value += 0.1;
},
onComplete() {
object.userData.isBw = false;
}
})
.set(object.material.uniforms.uMouse, { value: { x: 0.5, y: 0.5} }, 0)
.set(object.material.uniforms.uDirection, { value: 1.0 }, 0)
.fromTo(object.material.uniforms.uGrayscaleProgress, { value: 1 }, { value: 0 }, 0)
.to(object.material.uniforms.uRippleProgress, { keyframes: { value: [0, 1, 0] } }, 0);
}
onClick(e) {
// Convert click coordinates to normalized device coordinates (-1 to 1)
const normCoords = {
x: (e.x / window.innerWidth) * 2 - 1,
y: -(e.y / window.innerHeight) * 2 + 1,
};
// Set raycaster from the camera using the pointer's position
this.raycaster.setFromCamera(normCoords, this.camera);
// Get the first intersected object in the scene
const [intersection] = this.raycaster.intersectObjects(this.scene.children);
if (intersection) {
const { material, userData } = intersection.object;
if (this.activeObject && intersection.object !== this.activeObject && this.activeObject.userData.isBw) {
this.resetMaterial(this.activeObject)
// Stops timeline if active
if (this.activeObject.userData.tl?.isActive()) this.activeObject.userData.tl.kill();
// Cleans timeline
this.activeObject.userData.tl = null;
}
// Setup active object
this.activeObject = intersection.object;
// Only trigger animation if one is not already active
if (!userData.tl?.isActive()) {
// Toggle isBw state (black and white mode)
intersection.object.userData.isBw = !userData.isBw;
// Store the animation timeline on the object to avoid overlapping animations
userData.tl = this.animate(material, userData, intersection.uv);
}
}
}
}
src/js/demo1/PlanesMaterial.js
import { ShaderMaterial, Vector2 } from 'three';
import baseVertex from './base.vert?raw';
import baseFragment from './base.frag?raw';
export default class PlanesMaterial extends ShaderMaterial {
constructor(texture) {
super({
vertexShader: baseVertex,
fragmentShader: baseFragment,
uniforms: {
uGrayscaleProgress: { value: 0 },
uRippleProgress: { value: 0 },
uTime: { value: 0 },
uDirection: { value: 1 },
uMouse: { value: new Vector2(0.5, 0.5) },
uTexture: { value: texture },
},
});
}
}src/js/demo1/Stage.js
import {
Mesh,
OrthographicCamera,
PlaneGeometry,
Scene,
SRGBColorSpace,
TextureLoader,
WebGLRenderer,
} from 'three';
import { getWorldPositionFromDOM } from '../utils';
import PlanesMaterial from './PlanesMaterial';
import Effect from './Effect';
export default class Stage {
constructor(container) {
this.container = container;
this.DOMElements = [...this.container.querySelectorAll('img')];
this.renderer = new WebGLRenderer({
powerPreference: 'high-performance',
antialias: true,
alpha: true,
});
this.renderer.setPixelRatio(Math.min(1.5, window.devicePixelRatio));
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.domElement.classList.add('content__canvas');
this.container.appendChild(this.renderer.domElement);
this.scene = new Scene();
const { innerWidth: width, innerHeight: height } = window;
this.camera = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, -1000, 1000);
this.camera.position.z = 10;
this.setUpPlanes();
this.effect = this.initEffect();
}
setUpPlanes() {
this.DOMElements.forEach((image) => {
this.scene.add(this.generatePlane(image));
});
}
generatePlane(image, ) {
const loader = new TextureLoader();
const texture = loader.load(image.src);
texture.colorSpace = SRGBColorSpace;
const plane = new Mesh(
new PlaneGeometry(1, 1, 50, 50),
new PlanesMaterial(texture),
);
return plane;
}
initEffect() {
return new Effect(this.scene, this.camera);
}
resize() {
// Update camera props to fit the canvas size
const { innerWidth: screenWidth, innerHeight: screenHeight } = window;
this.camera.left = -screenWidth / 2;
this.camera.right = screenWidth / 2;
this.camera.top = screenHeight / 2;
this.camera.bottom = -screenHeight / 2;
this.camera.updateProjectionMatrix();
// Update also planes sizes
this.DOMElements.forEach((image, index) => {
const { width: imageWidth, height: imageHeight } = image.getBoundingClientRect();
this.scene.children[index].scale.set(imageWidth, imageHeight, 1);
});
// Update the render using the window sizes
this.renderer.setSize(screenWidth, screenHeight);
}
render() {
this.renderer.render(this.scene, this.camera);
// For each plane and each image update the position of the plane to match the DOM element position on page
this.DOMElements.forEach((image, index) => {
this.scene.children[index].position.copy(getWorldPositionFromDOM(image, this.camera));
});
}
}src/js/demo1/base.frag
varying vec2 vUv;
varying float vRipple;
uniform float uGrayscaleProgress;
uniform vec2 uMouse;
uniform float uDirection;
uniform sampler2D uTexture;
vec3 toGrayscale(vec3 color) {
float gray = dot(color, vec3(0.299, 0.587, 0.114));
return vec3(gray);
}
// Calculates the maximum distance from the given point to the 4 corners of the plane (in UV coordinates)
float getMaxDistFromCorners(vec2 coords) {
float dist_bl = distance(coords, vec2(0.0, 0.0)); // Bottom-Left
float dist_br = distance(coords, vec2(1.0, 0.0)); // Bottom-Right
float dist_tl = distance(coords, vec2(0.0, 1.0)); // Top-Left
float dist_tr = distance(coords, vec2(1.0, 1.0)); // Top-Right
// Returns the largest of the four distances
return max(dist_tl, max(dist_bl, max(dist_tr, dist_br)));
}
void main() {
vec4 diffuse = texture2D(uTexture, vUv);
vec3 grayscale = toGrayscale(diffuse.rgb);
float dist = distance(vUv, uMouse);
// Calculates the maximum possible distance from the mouse point to one of the 4 corners
float maxDist = getMaxDistFromCorners(uMouse);
float mask = smoothstep(uGrayscaleProgress - 0.1, uGrayscaleProgress, dist / maxDist);
vec3 color1 = uDirection > 0.0 ? diffuse.rgb : grayscale;
vec3 color2 = uDirection > 0.0 ? grayscale : diffuse.rgb;
// The mask always expands from the center outward
vec3 color = mix(color1, color2, mask);
color += vRipple * 2.;
gl_FragColor = vec4(color, diffuse.a);
}
src/js/demo1/base.vert
#define AMP 0.1
#define FREQ 8.0
#define PI 3.14159265359
varying vec2 vUv;
varying float vRipple;
uniform float uRippleProgress;
uniform float uTime;
uniform vec2 uMouse;
void main() {
vec3 pos = position;
float dist = distance(uv, uMouse);
float decay = clamp(dist, 8.0, 10.0);
float ripple = sin(-PI * FREQ * dist + uTime) * (AMP / decay);
ripple *= uRippleProgress;
pos.y += ripple;
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
vUv = uv;
vRipple = ripple;
}src/js/demo1/main.js
import { gsap } from 'gsap';
import { Draggable } from 'gsap/Draggable';
import { InertiaPlugin } from 'gsap/InertiaPlugin';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { debounce } from '../utils';
import Stage from './Stage';
import { preloadImages } from '../utils';
gsap.registerPlugin(Draggable, InertiaPlugin, ScrollTrigger);
const carouselWrapper = document.querySelector('.content');
const stage = new Stage(carouselWrapper);
gsap.ticker.add(stage.render.bind(stage));
function resize() {
stage.resize();
}
preloadImages().then(() => document.body.classList.remove('loading'));
window.addEventListener('load', resize);
window.addEventListener('resize', debounce(resize));src/js/demo2/Effect.js
import { gsap } from 'gsap';
import { Observer } from 'gsap/Observer';
import { Raycaster } from 'three';
gsap.registerPlugin(Observer);
export default class Effect {
constructor(scene, camera) {
this.scene = scene;
this.camera = camera;
// Store the currently intersected object
this.intersected = null;
// Raycaster for detecting intersections with 3D objects
this.raycaster = new Raycaster();
// Create a GSAP Observer to track pointer and touch movement
this.observer = Observer.create({
target: document.querySelector('.content__carousel'),
type: 'touch,pointer',
onMove: e => this.onMove(e),
onHoverEnd: () => this.hoverOut(),
});
}
hoverOut() {
if (!this.intersected) return;
// Stop any running tweens on the uMixFactor uniform
gsap.killTweensOf(this.intersected.material.uniforms.uMixFactor);
// Animate uMixFactor back to 0 smoothly
gsap.to(this.intersected.material.uniforms.uMixFactor, {
value: 0.0,
duration: 0.5,
ease: 'power3.out'
});
// Clear the intersected reference
this.intersected = null;
}
onMove(e) {
// Convert screen coordinates to normalized device coordinates (-1 to 1)
const normCoords = {
x: (e.x / window.innerWidth) * 2 - 1,
y: -(e.y / window.innerHeight) * 2 + 1,
};
// Update raycaster with current pointer position and camera
this.raycaster.setFromCamera(normCoords, this.camera);
// Check for intersections with objects in the scene
const [intersection] = this.raycaster.intersectObjects(this.scene.children);
if (intersection) {
// If an object is intersected, store a reference
this.intersected = intersection.object;
const { material } = intersection.object;
// Animate uniforms to create a hover effect
gsap.timeline()
.set(material.uniforms.uMouse, { value: intersection.uv }, 0)
.to(material.uniforms.uMixFactor, {
value: 1.0,
duration: 3,
ease: 'power3.out'
}, 0);
} else {
// If no object is intersected, reset
this.hoverOut();
}
}
}
src/js/demo2/PlanesMaterial.js
import { ShaderMaterial, Vector2 } from 'three';
import baseVertex from './base.vert?raw';
import baseFragment from './base.frag?raw';
export default class PlanesMaterial extends ShaderMaterial {
constructor(texture, textureBack, imageRatio) {
super({
vertexShader: baseVertex,
fragmentShader: baseFragment,
uniforms: {
uTexture: { value: texture },
uTextureBack: { value: textureBack },
uMixFactor: { value: 0.0 },
uAspect: { value: imageRatio },
uMouse: { value: new Vector2(0.5, 0.5) },
},
});
}
}src/js/demo2/Stage.js
import {
Mesh,
OrthographicCamera,
PlaneGeometry,
Scene,
SRGBColorSpace,
TextureLoader,
WebGLRenderer,
} from 'three';
import { getWorldPositionFromDOM } from '../utils';
import PlanesMaterial from './PlanesMaterial';
import Effect from './Effect';
export default class Stage {
constructor(container) {
this.container = container;
this.DOMElements = [...this.container.querySelectorAll('img')];
this.renderer = new WebGLRenderer({
powerPreference: 'high-performance',
antialias: true,
alpha: true,
});
this.renderer.setPixelRatio(Math.min(1.5, window.devicePixelRatio));
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.domElement.classList.add('content__canvas');
this.container.appendChild(this.renderer.domElement);
this.scene = new Scene();
const { innerWidth: width, innerHeight: height } = window;
this.camera = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, -1000, 1000);
this.camera.position.z = 10;
this.setUpPlanes();
this.effect = this.initEffect();
}
setUpPlanes() {
this.DOMElements.forEach((image) => {
this.scene.add(this.generatePlane(image));
});
}
generatePlane(image, ) {
const loader = new TextureLoader();
const texture = loader.load(image.src);
const textureBack = loader.load(image.dataset.back);
texture.colorSpace = SRGBColorSpace;
textureBack.colorSpace = SRGBColorSpace;
const { width, height } = image.getBoundingClientRect();
const plane = new Mesh(
new PlaneGeometry(1, 1),
new PlanesMaterial(texture, textureBack, height / width),
);
return plane;
}
initEffect() {
return new Effect(this.scene, this.camera);
}
resize() {
// Update camera props to fit the canvas size
const { innerWidth: screenWidth, innerHeight: screenHeight } = window;
this.camera.left = -screenWidth / 2;
this.camera.right = screenWidth / 2;
this.camera.top = screenHeight / 2;
this.camera.bottom = -screenHeight / 2;
this.camera.updateProjectionMatrix();
// Update also planes sizes
this.DOMElements.forEach((image, index) => {
const { width: imageWidth, height: imageHeight } = image.getBoundingClientRect();
this.scene.children[index].scale.set(imageWidth, imageHeight, 1);
});
// Update the render using the window sizes
this.renderer.setSize(screenWidth, screenHeight);
}
render() {
this.renderer.render(this.scene, this.camera);
// For each plane and each image update the position of the plane to match the DOM element position on page
this.DOMElements.forEach((image, index) => {
this.scene.children[index].position.copy(getWorldPositionFromDOM(image, this.camera));
});
}
}src/js/demo2/base.frag
uniform sampler2D uTexture;
uniform sampler2D uTextureBack;
uniform float uMixFactor;
uniform vec2 uMouse;
uniform float uAspect;
varying vec2 vUv;
void main() {
vec2 correctedUv = vec2(vUv.x, (vUv.y - 0.5) * uAspect + 0.5);
vec2 correctedMouse = vec2(uMouse.x, (uMouse.y - 0.5) * uAspect + 0.5);
// Calculate the distance from the current fragment to the mouse position
float distance = length(correctedUv - correctedMouse);
// Create a localized influence based on distance using smoothstep. Influence is strongest (1.0) at the mouse center, and fades to 0.0 outward
float influence = 1.0 - smoothstep(0.0, 0.5, distance);
// Modulate the global mix factor by the local influence
float finalMix = uMixFactor * influence;
// Sample both front and back textures using original UVs
vec4 textureFront = texture2D(uTexture, vUv);
vec4 textureBack = texture2D(uTextureBack, vUv);
// Blend the two textures based on the final mix factor
vec4 finalColor = mix(textureFront, textureBack, finalMix);
// Output the final color to the screen
gl_FragColor = finalColor;
}
src/js/demo2/base.vert
varying vec2 vUv;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vUv = uv;
}src/js/demo2/main.js
import { gsap } from 'gsap';
import { Draggable } from 'gsap/Draggable';
import { InertiaPlugin } from 'gsap/InertiaPlugin';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { debounce } from '../utils';
import Stage from './Stage';
import { preloadImages } from '../utils';
gsap.registerPlugin(Draggable, InertiaPlugin, ScrollTrigger);
const carouselWrapper = document.querySelector('.content');
const stage = new Stage(carouselWrapper);
gsap.ticker.add(stage.render.bind(stage));
function resize() {
stage.resize();
}
preloadImages().then(() => document.body.classList.remove('loading'));
window.addEventListener('load', resize);
window.addEventListener('resize', debounce(resize));src/js/demo3/Effect.js
import { gsap } from 'gsap';
import { Observer } from 'gsap/Observer';
import { Raycaster } from 'three';
export default class Effect {
constructor(scene, camera) {
this.scene = scene;
this.camera = camera;
this.active = null; // Currently active (pressed) object
this.prevActive = null; // Prev active (pressed) object
// Raycaster to detect pointer intersection with 3D objects
this.raycaster = new Raycaster();
// GSAP Observer listens for pointer/touch press, move, and release
this.observer = Observer.create({
target: document.querySelector('.content__carousel'),
type: 'touch,pointer',
onPress: e => this.onPress(e),
onMove: e => this.onMove(e),
onRelease: () => this.onRelease(),
});
// Continuously update the uTime uniform for the active object
gsap.ticker.add(() => {
if (this.active) {
this.active.material.uniforms.uTime.value += 0.1;
}
});
}
resetState(obj) {
obj.userData.isBw = !obj.userData.isBw;
obj.material.uniforms.uDirection.value = obj.userData.isBw ? 1.0 : -1.0;
obj.material.uniforms.uGrayscaleProgress.value = 0;
}
resetMaterial(obj) {
gsap.killTweensOf(obj.material.uniforms.uGrayscaleProgress);
obj.material.uniforms.uDirection.value = 1.0;
obj.material.uniforms.uMouse.value = { x: 0.5, y: 0.5};
const tl = gsap.timeline({
onComplete: () => this.resetState(obj)
});
tl.fromTo(obj.material.uniforms.uGrayscaleProgress, { value: 0.0 }, { value: 1.0 }, 0.3);
}
async onActiveEnter() {
// Kill any ongoing grayscale animations
gsap.killTweensOf(this.active.material.uniforms.uGrayscaleProgress);
// Animate to grayscale value 0.35 over 1 second
await gsap.fromTo(this.active.material.uniforms.uGrayscaleProgress, { value: 0.0 }, {
value: 0.35,
duration: 0.5,
});
if (this.prevActive && this.prevActive !== this.active && this.prevActive.userData.isBw) this.resetMaterial(this.prevActive)
// Animate to full grayscale (1.0), then reset and toggle direction
gsap.to(this.active.material.uniforms.uGrayscaleProgress, {
value: 1,
duration: 0.5,
delay: 0.12,
ease: 'power2.in',
onComplete: () => {
this.resetState(this.active);
this.prevActive = this.active;
},
});
}
onActiveLeve(mesh) {
// Kill any ongoing grayscale animations
gsap.killTweensOf(mesh.material.uniforms.uGrayscaleProgress);
// Animate grayscale back to 0, and update uTime during the process
gsap.to(mesh.material.uniforms.uGrayscaleProgress, {
value: 0,
onUpdate: () => {
mesh.material.uniforms.uTime.value += 0.1;
},
});
}
getIntersection(e) {
// Convert screen coordinates to normalized device coordinates (-1 to 1)
const normCoords = {
x: (e.x / window.innerWidth) * 2 - 1,
y: -(e.y / window.innerHeight) * 2 + 1,
};
// Update the raycaster with pointer position and camera
this.raycaster.setFromCamera(normCoords, this.camera);
// Check for intersections with scene objects
const [intersection] = this.raycaster.intersectObjects(this.scene.children);
return intersection;
}
onPress(e) {
const intersection = this.getIntersection(e);
if (intersection) {
this.active = intersection.object;
// Start the grayscale transition animation
this.onActiveEnter(this.active);
}
}
onRelease() {
if (this.active) {
const prevActive = this.active;
this.active = null;
// Reset animation on the previously active object
this.onActiveLeve(prevActive);
}
}
onMove(e) {
const intersection = this.getIntersection(e);
if (intersection) {
// Update shader uniform with current pointer UV coordinates
const { material } = intersection.object;
gsap.set(material.uniforms.uMouse, { value: intersection.uv });
} else {
// If pointer is not over an object anymore, release/reset
this.onRelease();
}
}
}
src/js/demo3/PlanesMaterial.js
import { ShaderMaterial, Vector2 } from 'three';
import baseVertex from './base.vert?raw';
import baseFragment from './base.frag?raw';
export default class PlanesMaterial extends ShaderMaterial {
constructor(texture) {
super({
vertexShader: baseVertex,
fragmentShader: baseFragment,
uniforms: {
uGrayscaleProgress: { value: 0 },
uDirection: { value: 0 },
uTime: { value: 0 },
uMouse: { value: new Vector2(0.5, 0.5) },
uTexture: { value: texture },
},
});
}
}src/js/demo3/Stage.js
import {
Mesh,
OrthographicCamera,
PlaneGeometry,
Scene,
SRGBColorSpace,
TextureLoader,
WebGLRenderer,
} from 'three';
import { getWorldPositionFromDOM } from '../utils';
import PlanesMaterial from './PlanesMaterial';
import Effect from './Effect';
export default class Stage {
constructor(container) {
this.container = container;
this.DOMElements = [...this.container.querySelectorAll('img')];
this.renderer = new WebGLRenderer({
powerPreference: 'high-performance',
antialias: true,
alpha: true,
});
this.renderer.setPixelRatio(Math.min(1.5, window.devicePixelRatio));
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.domElement.classList.add('content__canvas');
this.container.appendChild(this.renderer.domElement);
this.scene = new Scene();
const { innerWidth: width, innerHeight: height } = window;
this.camera = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, -1000, 1000);
this.camera.position.z = 10;
this.setUpPlanes();
this.effect = this.initEffect();
}
setUpPlanes() {
this.DOMElements.forEach((image) => {
this.scene.add(this.generatePlane(image));
});
}
generatePlane(image, ) {
const loader = new TextureLoader();
const texture = loader.load(image.src);
texture.colorSpace = SRGBColorSpace;
const plane = new Mesh(
new PlaneGeometry(1, 1),
new PlanesMaterial(texture),
);
return plane;
}
initEffect() {
return new Effect(this.scene, this.camera);
}
resize() {
// Update camera props to fit the canvas size
const { innerWidth: screenWidth, innerHeight: screenHeight } = window;
this.camera.left = -screenWidth / 2;
this.camera.right = screenWidth / 2;
this.camera.top = screenHeight / 2;
this.camera.bottom = -screenHeight / 2;
this.camera.updateProjectionMatrix();
// Update also planes sizes
this.DOMElements.forEach((image, index) => {
const { width: imageWidth, height: imageHeight } = image.getBoundingClientRect();
this.scene.children[index].scale.set(imageWidth, imageHeight, 1);
});
// Update the render using the window sizes
this.renderer.setSize(screenWidth, screenHeight);
}
render() {
this.renderer.render(this.scene, this.camera);
// For each plane and each image update the position of the plane to match the DOM element position on page
this.DOMElements.forEach((image, index) => {
this.scene.children[index].position.copy(getWorldPositionFromDOM(image, this.camera));
});
}
}src/js/demo3/base.frag
#define PI 3.14159265359
varying vec2 vUv;
varying float vDist;
uniform float uGrayscaleProgress;
uniform float uDirection;
uniform float uTime;
uniform vec2 uMouse;
uniform sampler2D uTexture;
vec3 toGrayscale(vec3 color) {
float gray = dot(color, vec3(0.299, 0.587, 0.114));
return vec3(gray);
}
// Calculates the maximum distance from the given point to the 4 corners of the plane (in UV coordinates)
float getMaxDistFromCorners(vec2 coords) {
float dist_bl = distance(coords, vec2(0.0, 0.0)); // Bottom-Left
float dist_br = distance(coords, vec2(1.0, 0.0)); // Bottom-Right
float dist_tl = distance(coords, vec2(0.0, 1.0)); // Top-Left
float dist_tr = distance(coords, vec2(1.0, 1.0)); // Top-Right
// Returns the largest of the four distances
return max(dist_tl, max(dist_bl, max(dist_tr, dist_br)));
}
// Function to generate a random value from a vec2
float random (vec2 st) {
return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
}
// 2D noise function
float noise (vec2 st) {
vec2 i = floor(st);
vec2 f = fract(st);
float a = random(i);
float b = random(i + vec2(1.0, 0.0));
float c = random(i + vec2(0.0, 1.0));
float d = random(i + vec2(1.0, 1.0));
vec2 u = f * f * (3.0 - 2.0 * f);
return mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.y * u.x;
}
void main() {
float noisy = (noise(vUv * 25.0 + uTime * 0.5) - 0.5) * 0.05; // Noise centered around zero
float distortionStrength = sin(uGrayscaleProgress * PI) * 0.5;
vec2 distortedUv = vUv + vec2(noisy) * distortionStrength;
vec4 diffuse = texture2D(uTexture, uDirection > 0.0 ? distortedUv : vUv);
vec3 textureGrayscale = texture2D(uTexture, uDirection > 0.0 ? vUv : distortedUv).rgb;
vec3 grayscale = toGrayscale(textureGrayscale);
vec2 toCenter = vUv - uMouse;
float dist = length(toCenter);
float distortedDist = dist + noisy;
// Calculates the maximum possible distance from the mouse point to one of the 4 corners
float maxDist = getMaxDistFromCorners(uMouse);
float mask = smoothstep(uGrayscaleProgress - 0.1, uGrayscaleProgress, distortedDist / maxDist);
vec3 color1 = uDirection > 0.0 ? diffuse.rgb : grayscale;
vec3 color2 = uDirection > 0.0 ? grayscale : diffuse.rgb;
vec3 color = mix(color1, color2, mask);
gl_FragColor = vec4(color, diffuse.a);
}
src/js/demo3/base.vert
varying vec2 vUv;
varying float vDist;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}src/js/demo3/main.js
import { gsap } from 'gsap';
import { Draggable } from 'gsap/Draggable';
import { InertiaPlugin } from 'gsap/InertiaPlugin';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { debounce } from '../utils';
import Stage from './Stage';
import { preloadImages } from '../utils';
gsap.registerPlugin(Draggable, InertiaPlugin, ScrollTrigger);
const carouselWrapper = document.querySelector('.content');
const stage = new Stage(carouselWrapper);
gsap.ticker.add(stage.render.bind(stage));
function resize() {
stage.resize();
}
preloadImages().then(() => document.body.classList.remove('loading'));
window.addEventListener('load', resize);
window.addEventListener('resize', debounce(resize));src/js/demo4/Effect.js
import { gsap } from 'gsap';
import { Vector3, MathUtils } from 'three';
import { debounce } from '../utils';
export default class Effect {
constructor(scene, camera) {
this.scene = scene;
this.camera = camera;
// Get all child objects (tiles) from the scene
this.tiles = scene.children;
// Reference to the scroll update callback function
this.callback = this.scrollUpdateCallback;
// Center of the screen in X axes
this.centerX = window.innerWidth / 2
window.addEventListener('resize', debounce(() => this.centerX = window.innerWidth / 2));
}
scrollUpdateCallback() {
this.tiles.forEach(tile => {
// Project tile's 3D position to 2D screen space
const worldPosition = tile.getWorldPosition(new Vector3());
const vector = worldPosition.clone().project(this.camera);
// Convert normalized device coordinates to screen coordinates (pixels)
const screenX = (vector.x * 0.5 + 0.5) * window.innerWidth;
// Calculate distance from the tile to the center of the screen
const distance = Math.abs(screenX - this.centerX);
// Maximum possible distance from center to corner of the screen
const maxDistance = window.innerWidth / 2;
// Normalize distance and scale to get blur amount (0.0 to 10.0)
const blurAmount = MathUtils.clamp(distance / maxDistance * 5, 0.0, 5.0);
// console.log('Distance:', distance, 'Blur:', blurAmount);
// Animate the uBlurAmount uniform of the tile's material rounded to the nearest even number for a cleaner effect
gsap.to(tile.material.uniforms.uBlurAmount, {
value: Math.round(blurAmount / 2) * 2,
duration: 1.5,
ease: 'power3.out'
});
});
}
}src/js/demo4/PlanesMaterial.js
import { ShaderMaterial } from 'three';
import baseVertex from './base.vert?raw';
import baseFragment from './base.frag?raw';
export default class PlanesMaterial extends ShaderMaterial {
constructor(texture) {
super({
vertexShader: baseVertex,
fragmentShader: baseFragment,
uniforms: {
uTexture: { value: texture },
uBlurAmount: { value: 0.0 },
},
});
}
}src/js/demo4/Stage.js
import {
Mesh,
OrthographicCamera,
PlaneGeometry,
Scene,
SRGBColorSpace,
TextureLoader,
WebGLRenderer,
} from 'three';
import { getWorldPositionFromDOM } from '../utils';
import PlanesMaterial from './PlanesMaterial';
import Effect from './Effect';
export default class Stage {
constructor(container) {
this.container = container;
this.DOMElements = [...this.container.querySelectorAll('img')];
this.renderer = new WebGLRenderer({
powerPreference: 'high-performance',
antialias: true,
alpha: true,
});
this.renderer.setPixelRatio(Math.min(1.5, window.devicePixelRatio));
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.domElement.classList.add('content__canvas');
this.container.appendChild(this.renderer.domElement);
this.scene = new Scene();
const { innerWidth: width, innerHeight: height } = window;
this.camera = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, -1000, 1000);
this.camera.position.z = 10;
this.setUpPlanes();
this.effect = this.initEffect();
}
setUpPlanes() {
this.DOMElements.forEach((image) => {
this.scene.add(this.generatePlane(image));
});
}
generatePlane(image, ) {
const loader = new TextureLoader();
const texture = loader.load(image.src);
texture.colorSpace = SRGBColorSpace;
const plane = new Mesh(
new PlaneGeometry(1, 1, 50, 50),
new PlanesMaterial(texture),
);
return plane;
}
initEffect() {
return new Effect(this.scene, this.camera);
}
resize() {
// Update camera props to fit the canvas size
const { innerWidth: screenWidth, innerHeight: screenHeight } = window;
this.camera.left = -screenWidth / 2;
this.camera.right = screenWidth / 2;
this.camera.top = screenHeight / 2;
this.camera.bottom = -screenHeight / 2;
this.camera.updateProjectionMatrix();
// Update also planes sizes
this.DOMElements.forEach((image, index) => {
const { width: imageWidth, height: imageHeight } = image.getBoundingClientRect();
this.scene.children[index].scale.set(imageWidth, imageHeight, 1);
});
// Update the render using the window sizes
this.renderer.setSize(screenWidth, screenHeight);
}
render() {
this.renderer.render(this.scene, this.camera);
// For each plane and each image update the position of the plane to match the DOM element position on page
this.DOMElements.forEach((image, index) => {
this.scene.children[index].position.copy(getWorldPositionFromDOM(image, this.camera));
});
}
}src/js/demo4/base.frag
uniform sampler2D uTexture;
uniform float uBlurAmount;
varying vec2 vUv;
// Performs a single pass Kawase blur by sampling 4 neighboring pixels with a given offset
vec4 kawaseBlur(sampler2D tex, vec2 uv, float offset) {
// Calculate the size of one texel (pixel) in UV coordinates
vec2 texelSize = vec2(1.0) / vec2(textureSize(tex, 0));
vec4 color = vec4(0.0);
// Sample the texture at 4 offset positions around the current UV coordinate
color += texture2D(tex, uv + vec2(offset, offset) * texelSize);
color += texture2D(tex, uv + vec2(-offset, offset) * texelSize);
color += texture2D(tex, uv + vec2(offset, -offset) * texelSize);
color += texture2D(tex, uv + vec2(-offset, -offset) * texelSize);
// Average the samples to get the blur color for this pass
return color * 0.25;
}
// Combines multiple Kawase blur passes with increasing offsets to create a stronger blur effect
vec4 multiPassKawaseBlur(sampler2D tex, vec2 uv, float blurStrength) {
// Original color without blur
vec4 baseTexture = texture2D(tex, uv);
// Perform three Kawase blur passes with different offsets scaled by blurStrength
vec4 blur1 = kawaseBlur(tex, uv, 1.0 + blurStrength * 1.5);
vec4 blur2 = kawaseBlur(tex, uv, 2.0 + blurStrength);
vec4 blur3 = kawaseBlur(tex, uv, 3.0 + blurStrength * 2.5);
// Calculate interpolation factors to smoothly blend between blur passes based on blurStrength
float t1 = smoothstep(0.0, 3.0, blurStrength);
float t2 = smoothstep(3.0, 7.0, blurStrength);
// Blend blur passes progressively
vec4 blurredTexture = mix(blur1, blur2, t1);
blurredTexture = mix(blurredTexture, blur3, t2);
// Calculate mix factor for blending the original and blurred colors
float mixFactor = smoothstep(0.0, 1.0, blurStrength);
// Return the final color, interpolating between original and blurred based on mixFactor
return mix(baseTexture, blurredTexture, mixFactor);
}
void main() {
// Apply multi-pass Kawase blur with the given blur amount
vec4 color = multiPassKawaseBlur(uTexture, vUv, uBlurAmount);
gl_FragColor = color;
}
src/js/demo4/base.vert
varying vec2 vUv;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
vUv = uv;
}src/js/demo4/main.js
import { gsap } from 'gsap';
import { Draggable } from 'gsap/Draggable';
import { InertiaPlugin } from 'gsap/InertiaPlugin';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { debounce, preloadImages } from '../utils';
import Stage from './Stage';
gsap.registerPlugin(Draggable, InertiaPlugin, ScrollTrigger);
const carouselWrapper = document.querySelector('.content');
const carouselInnerRef = document.querySelector('.content__carousel-inner');
const stage = new Stage(carouselWrapper);
let scrollPos = 0;
const draggable = new Draggable(carouselInnerRef, {
type: 'x',
inertia: true,
dragResistance: 0.5,
edgeResistance: 0.5,
throwResistance: 0.5,
throwProps: true,
onDrag() {
const progress = gsap.utils.normalize(draggable.maxX, draggable.minX, draggable.x);
scrollPos = scrollTriggerInstance.start + (scrollTriggerInstance.end - scrollTriggerInstance.start) * progress;
scrollTriggerInstance.scroll(scrollPos);
if (stage.effect.callback) stage.effect.callback();
},
onThrowUpdate() {
const progress = gsap.utils.normalize(draggable.maxX, draggable.minX, draggable.x);
scrollPos = scrollTriggerInstance.start + (scrollTriggerInstance.end - scrollTriggerInstance.start) * progress;
scrollTriggerInstance.scroll(scrollPos);
if (stage.effect.callback) stage.effect.callback();
},
});
let maxScroll = Math.abs(Math.min(0, window.innerWidth - carouselInnerRef.scrollWidth));
const scrollTriggerInstance = ScrollTrigger.create({
trigger: carouselWrapper,
start: 'top top',
end: `+=${2.5 * maxScroll}`,
pin: true,
scrub: 0.05,
anticipatePin: 1,
invalidateOnRefresh: true,
onUpdate(e) {
const x = -maxScroll * e.progress;
gsap.set(carouselInnerRef, { x });
draggable.x = x;
draggable.update();
if (stage.effect.callback) stage.effect.callback();
}
});
gsap.ticker.add(stage.render.bind(stage));
function resize() {
const innerWidth = carouselInnerRef.scrollWidth;
const viewportWidth = window.innerWidth;
maxScroll = Math.abs(Math.min(0, viewportWidth - innerWidth));
draggable.applyBounds({ minX: -maxScroll, maxX: 0 });
scrollTriggerInstance.refresh();
stage.resize();
}
preloadImages().then(() => document.body.classList.remove('loading'));
window.addEventListener('load', resize);
window.addEventListener('resize', debounce(resize));src/js/libs/imagesloaded.pkgd.min.js
/*!
* imagesLoaded PACKAGED v5.0.0
* JavaScript is all like "You images are done yet or what?"
* MIT License
*/
!function(t,e){"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,(function(){function t(){}let e=t.prototype;return e.on=function(t,e){if(!t||!e)return this;let i=this._events=this._events||{},s=i[t]=i[t]||[];return s.includes(e)||s.push(e),this},e.once=function(t,e){if(!t||!e)return this;this.on(t,e);let i=this._onceEvents=this._onceEvents||{};return(i[t]=i[t]||{})[e]=!0,this},e.off=function(t,e){let i=this._events&&this._events[t];if(!i||!i.length)return this;let s=i.indexOf(e);return-1!=s&&i.splice(s,1),this},e.emitEvent=function(t,e){let i=this._events&&this._events[t];if(!i||!i.length)return this;i=i.slice(0),e=e||[];let s=this._onceEvents&&this._onceEvents[t];for(let n of i){s&&s[n]&&(this.off(t,n),delete s[n]),n.apply(this,e)}return this},e.allOff=function(){return delete this._events,delete this._onceEvents,this},t})),
/*!
* imagesLoaded v5.0.0
* JavaScript is all like "You images are done yet or what?"
* MIT License
*/
function(t,e){"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter")):t.imagesLoaded=e(t,t.EvEmitter)}("undefined"!=typeof window?window:this,(function(t,e){let i=t.jQuery,s=t.console;function n(t,e,o){if(!(this instanceof n))return new n(t,e,o);let r=t;var h;("string"==typeof t&&(r=document.querySelectorAll(t)),r)?(this.elements=(h=r,Array.isArray(h)?h:"object"==typeof h&&"number"==typeof h.length?[...h]:[h]),this.options={},"function"==typeof e?o=e:Object.assign(this.options,e),o&&this.on("always",o),this.getImages(),i&&(this.jqDeferred=new i.Deferred),setTimeout(this.check.bind(this))):s.error(`Bad element for imagesLoaded ${r||t}`)}n.prototype=Object.create(e.prototype),n.prototype.getImages=function(){this.images=[],this.elements.forEach(this.addElementImages,this)};const o=[1,9,11];n.prototype.addElementImages=function(t){"IMG"===t.nodeName&&this.addImage(t),!0===this.options.background&&this.addElementBackgroundImages(t);let{nodeType:e}=t;if(!e||!o.includes(e))return;let i=t.querySelectorAll("img");for(let t of i)this.addImage(t);if("string"==typeof this.options.background){let e=t.querySelectorAll(this.options.background);for(let t of e)this.addElementBackgroundImages(t)}};const r=/url\((['"])?(.*?)\1\)/gi;function h(t){this.img=t}function d(t,e){this.url=t,this.element=e,this.img=new Image}return n.prototype.addElementBackgroundImages=function(t){let e=getComputedStyle(t);if(!e)return;let i=r.exec(e.backgroundImage);for(;null!==i;){let s=i&&i[2];s&&this.addBackground(s,t),i=r.exec(e.backgroundImage)}},n.prototype.addImage=function(t){let e=new h(t);this.images.push(e)},n.prototype.addBackground=function(t,e){let i=new d(t,e);this.images.push(i)},n.prototype.check=function(){if(this.progressedCount=0,this.hasAnyBroken=!1,!this.images.length)return void this.complete();let t=(t,e,i)=>{setTimeout((()=>{this.progress(t,e,i)}))};this.images.forEach((function(e){e.once("progress",t),e.check()}))},n.prototype.progress=function(t,e,i){this.progressedCount++,this.hasAnyBroken=this.hasAnyBroken||!t.isLoaded,this.emitEvent("progress",[this,t,e]),this.jqDeferred&&this.jqDeferred.notify&&this.jqDeferred.notify(this,t),this.progressedCount===this.images.length&&this.complete(),this.options.debug&&s&&s.log(`progress: ${i}`,t,e)},n.prototype.complete=function(){let t=this.hasAnyBroken?"fail":"done";if(this.isComplete=!0,this.emitEvent(t,[this]),this.emitEvent("always",[this]),this.jqDeferred){let t=this.hasAnyBroken?"reject":"resolve";this.jqDeferred[t](this)}},h.prototype=Object.create(e.prototype),h.prototype.check=function(){this.getIsImageComplete()?this.confirm(0!==this.img.naturalWidth,"naturalWidth"):(this.proxyImage=new Image,this.img.crossOrigin&&(this.proxyImage.crossOrigin=this.img.crossOrigin),this.proxyImage.addEventListener("load",this),this.proxyImage.addEventListener("error",this),this.img.addEventListener("load",this),this.img.addEventListener("error",this),this.proxyImage.src=this.img.currentSrc||this.img.src)},h.prototype.getIsImageComplete=function(){return this.img.complete&&this.img.naturalWidth},h.prototype.confirm=function(t,e){this.isLoaded=t;let{parentNode:i}=this.img,s="PICTURE"===i.nodeName?i:this.img;this.emitEvent("progress",[this,s,e])},h.prototype.handleEvent=function(t){let e="on"+t.type;this[e]&&this[e](t)},h.prototype.onload=function(){this.confirm(!0,"onload"),this.unbindEvents()},h.prototype.onerror=function(){this.confirm(!1,"onerror"),this.unbindEvents()},h.prototype.unbindEvents=function(){this.proxyImage.removeEventListener("load",this),this.proxyImage.removeEventListener("error",this),this.img.removeEventListener("load",this),this.img.removeEventListener("error",this)},d.prototype=Object.create(h.prototype),d.prototype.check=function(){this.img.addEventListener("load",this),this.img.addEventListener("error",this),this.img.src=this.url,this.getIsImageComplete()&&(this.confirm(0!==this.img.naturalWidth,"naturalWidth"),this.unbindEvents())},d.prototype.unbindEvents=function(){this.img.removeEventListener("load",this),this.img.removeEventListener("error",this)},d.prototype.confirm=function(t,e){this.isLoaded=t,this.emitEvent("progress",[this,this.element,e])},n.makeJQueryPlugin=function(e){(e=e||t.jQuery)&&(i=e,i.fn.imagesLoaded=function(t,e){return new n(this,t,e).jqDeferred.promise(i(this))})},n.makeJQueryPlugin(),n}));src/js/utils.js
import { Vector3 } from 'three';
const preloadImages = (selector = 'img') => {
return new Promise((resolve) => imagesLoaded(document.querySelectorAll(selector), { background: true }, resolve));
};
const getWorldPositionFromDOM = (element, camera) => {
const rect = element.getBoundingClientRect();
const xNDC = (rect.left + rect.width / 2) / window.innerWidth * 2 - 1;
const yNDC = -((rect.top + rect.height / 2) / window.innerHeight * 2 - 1);
const xWorld = xNDC * (camera.right - camera.left) / 2;
const yWorld = yNDC * (camera.top - camera.bottom) / 2;
return new Vector3(xWorld, yWorld, 0);
};
export const debounce = (callback, delay = 250) => {
let timeoutID;
return (...args) => {
clearTimeout(timeoutID);
timeoutID = setTimeout(() => {
timeoutID = null;
callback(...args);
}, delay);
};
};
export { preloadImages, getWorldPositionFromDOM };vite.config.js
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';
import { defineConfig } from 'vite';
import glsl from 'vite-plugin-glsl';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export default defineConfig({
base: './', // 👈 this makes assets relative
plugins: [glsl()],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
build: {
rollupOptions: {
input: {
demo1: resolve(__dirname, 'index.html'),
demo2: resolve(__dirname, 'index2.html'),
demo3: resolve(__dirname, 'index3.html'),
demo4: resolve(__dirname, 'index4.html'),
},
},
},
});
Media credits and license evidence실행 안내·자료
README.md
## Credits
- Images generated with [Midjourney](https://midjourney.com)
## License
[MIT](LICENSE)
Made with :blue_heart: by [Codrops](http://www.codrops.com)
LICENSE실행 안내·자료
MIT License
Copyright (c) 2025 Andrea Biason
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Bundled dependency licenses실행 안내·자료
GSAP standard license snapshot
Source: https://gsap.com/community/standard-license/
Retrieved: 2026-09-22T04:22:49.089Z
Original distribution copyright and version headers remain in the runtime code.
Standard "No Charge" GSAP License
I. DEFINITIONS
“GSAP License” means the terms and conditions of this GSAP Software License Agreement.
"GSAP Products" means any Software made available at gsap.com (https://gsap.com) or any successor sites, including but not limited to the GSAP animation library and related plugins, tools, or extensions.
"Permitted Uses" means the implementation and/or use of GSAP Products on any website, web application, or digital interface by any person or entity (which may include, for clarity, those of companies that compete with Webflow in other areas of business).
"Prohibited Uses" means any implementation and/or use of GSAP Products in tools that allow users to build visual animations without code that encourages, induces, or materially assists in creating a solution that competes with Webflow’s visual animation building capabilities.
"Competitive Products" means any software, tool, or service that enables users to create, edit, or manage animations through a visual interface or builder similar to Webflow (https://webflow.com).
II. GRANT OF LICENSE
Subject to the terms and conditions of this GSAP License, Webflow grants you a non-exclusive, worldwide license to use, reproduce, display, and implement GSAP Products solely for Permitted Uses.
III. RESTRICTIONS
You may not:
Use any GSAP Products for any Prohibited Uses without prior written consent;
Reverse engineer any GSAP Products for the purpose of creating Competitive Products;
Remove or alter any proprietary notices or branding from GSAP Products.
IV. OWNERSHIP AND INTELLECTUAL PROPERTY
All intellectual property rights in GSAP Products, including but not limited to copyright, patents, trademarks, and trade secrets, remain the exclusive property of Webflow. This GSAP License does not transfer any ownership rights in GSAP Products to you.
V. TERMINATION
Webflow may terminate this GSAP License and revoke your access in its discretion if you fail to comply with any of these terms and conditions. Upon termination, you must cease all use of GSAP Products and destroy all copies in your possession.
VI. MISCELLANEOUS PROVISIONS
General: This GSAP License is incorporated into and subject to Webflow’s Terms of Service available here (https://webflow.com/legal/terms) ("Terms of Service"). In the event of any conflict or inconsistency between this GSAP License and the Terms of Service, the terms of this GSAP License shall govern in relation to your use of any GSAP Products.
Amendments: Webflow reserves the right to update or modify this GSAP License at any time by posting the revised terms on this website, provided that any such updates or modifications shall not result in any material degradation to the security, integrity, or functionality of any GSAP Products. You understand and agree that your continued use of any GSAP Products after such revisions to this GSAP License constitutes your acceptance of this GSAP License as revised. If you do not accept the revised GSAP License, you are prohibited from using versions of the GSAP Products released after the effective date of the revised GSAP License (as well as any updates made to previous versions). Notwithstanding, you may continue using previous versions of GSAP Products under the applicable terms licensed to you prior to the effective date of the revised GSAP License (for clarity, excluding any updates made thereto).
No Waiver: Failure of Webflow to enforce any provision of this GSAP License shall not constitute a waiver of future enforcement of that or any other provision.
FAQ
Is it acceptable for AI tools like ChatGPT, Cursor, Lovable, Webstudio, etc. to generate GSAP code?
Absolutely! AI-generated code is not a "Prohibited Use".
What if a WordPress plugin or theme or other niche tool allows users to create GSAP-driven effects through a visual interface? Is that prohibited?
We want to encourage developers to build on top of GSAP, including visual tools that don't directly compete with Webflow's rich animation-building capabilities. If you are not sure if your product might be considered a "Prohibited Use", feel free to contact us (https://gsap.com/contact) so we can talk through it!
Can I really use GSAP in commercial projects without paying anything?
Yes, really! Commercial usage is covered under the standard license. All of GSAP including the plugins that were formerly "members-only" like SplitText (https://gsap.com/docs/v3/Plugins/SplitText/) and MorphSVG (https://gsap.com/docs/v3/Plugins/MorphSVGPlugin) can be used in commercial projects at no charge. Enjoy! 💚
Effective date: April 30, 2025
Last modified date: May 30, 2025
Copyright (©) 2025, Webflow
three@0.180.0 — LICENSE
The MIT License
Copyright © 2010-2025 three.js authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
BEHIND THE EXAMPLE
이 장면을 만드는 원리
tween 갱신 횟수로 증가하는 셰이더 시간
화면 크기·입력·동시 작업을 고정하고 실제 렌더링 실패와 비용을 관찰합니다.
- 이 예제에서는
- 첫 Effect의 animate와 resetMaterial은 onUpdate마다 uTime에 0.1을 더합니다. 그 값은 실제 경과 초가 아니라 콜백 횟수에 의존하며 ripple과 grayscale 값도 함께 바뀝니다.
