スクロールして指定の位置に来たら、画像がカッコよく表示されるアニメーションをつけます。
1. クラス「anime-img」を画像ウィジットにつけとく
2. 以下のJSを入れる
(このコードの上にGSAP読み込みコードを入れてください。)
HTML
<script>
document.addEventListener("DOMContentLoaded", () => {
gsap.registerPlugin(ScrollTrigger);
const images = document.querySelectorAll('.anime-img');
images.forEach((img) => {
const parent = img.parentElement;
if (window.getComputedStyle(parent).position === 'static') {
parent.style.position = 'relative';
}
if (window.getComputedStyle(img).position === 'static') {
img.style.position = 'relative';
}
img.style.zIndex = '2';
img.style.clipPath = 'inset(0 100% 0 0)';
img.style.webkitClipPath = 'inset(0 100% 0 0)';
const bg = document.createElement('div');
bg.style.position = 'absolute';
bg.style.backgroundColor = '#000F12'; //★背景色
bg.style.zIndex = '1';
bg.style.transformOrigin = 'left center';
bg.style.transform = 'scaleX(0)';
bg.style.pointerEvents = 'none';
parent.appendChild(bg);
const updateBgRect = () => {
bg.style.top = img.offsetTop + 'px';
bg.style.left = img.offsetLeft + 'px';
bg.style.width = img.offsetWidth + 'px';
bg.style.height = img.offsetHeight + 'px';
bg.style.borderRadius = window.getComputedStyle(img).borderRadius;
};
updateBgRect();
window.addEventListener('resize', updateBgRect);
if (typeof ResizeObserver !== 'undefined') {
const ro = new ResizeObserver(updateBgRect);
ro.observe(img);
} else {
img.addEventListener('load', updateBgRect);
}
const tl = gsap.timeline({
scrollTrigger: {
trigger: img,
start: "top 70%",
}
});
const ease = "expo.out";
tl.to(bg, {
scaleX: 1,
duration: 0.5, //★速さ調整
ease: ease
})
.to(img, {
clipPath: 'inset(0 0% 0 0)',
webkitClipPath: 'inset(0 0% 0 0)',
duration: 0.5, //★速さ調整
ease: ease
}, ">");
});
});
</script>