본문 바로가기
Tutorial/Portfolio

자연스럽게 변하는 배경색 변경 효과 만들어보기

by @webs 2023. 1. 5.

자연스럽게 변하는 배경색 변경 효과 만들어보기

Tutorial/Portfolio

자연스럽게 변하는 배경색 변경 효과 만들어보기

by @webs 2022. 12. 26.
Tutorial
배경 색 + 글씨 색 변경하기 + 스므스 효과 주기
난이도 중간

소개

안녕하세요🤭 이번에 변경색으로 자연스럽게 변경하는 효과를 만들어 보겠습니다. 섹션이 넘어갈 때 배경색을 스므스하게 변경해주면 고급스러운 느낌을 줄 수 있습니다. 당연히 이번에도 GSAP1는 당연히 사용하게 되구요! 스므스 효과는 Lenis2를 사용하겠습니다. 아~~ 참고로 이미지는 unsplash3에서 가져왔습니다.


01. 기본 코딩

기본 구조부터 셋팅을 합시다. 🥳 6개의 섹션이 있다고 가정하고 구조화하겠습니다.

<main id="main">
    <section id="section1">
    </section>
    <!-- //section1 -->

    <section id="section2">
    </section>
    <!-- //section2 -->

    <section id="section3">
    </section>
    <!-- //section3 -->

    <section id="section4">
    </section>
    <!-- //section4 -->

    <section id="section5">
    </section>
    <!-- //section5 -->

    <section id="section6">
    </section>
    <!-- //section6 -->
</main>

그럼 CSS도 셋팅해주겠습니다. 기본 설정도 간단하게 넣어주고, 배경색을 넣어주겠습니다. 색은 임의로 넣어봤습니다.

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
#main > section {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}
#section1 {
    background-color: #2c4855;
}
#section2 {
    background-color: #e3c4b8;
}
#section3 {
    background-color: #947e75;
}
#section4 {
    background-color: #a16a0f;
}
#section5 {
    background-color: #354E5F;
}
#section6 {
    background-color: #c0621a;
}

이번에는 각 섹션안에 글씨와 이미지를 넣어주겠습니다.

<main id="main">
    <section id="section1">
        <div class="text__inner">
            <div class="img img1"></div>
            <div class="txt1">Passion</div>
            <div class="txt2">Creative</div>
            <div class="txt3">Shining</div>
        </div>
    </section>
    <!-- //section1 -->

    <section id="section2">
        <div class="text__inner">
            <div class="img img2"></div>
            <div class="txt1">Passion</div>
            <div class="txt2">Creative</div>
            <div class="txt3">Shining</div>
        </div>
    </section>
    <!-- //section2 -->

    <section id="section3">
        <div class="text__inner">
            <div class="img img3"></div>
            <div class="txt1">Passion</div>
            <div class="txt2">Creative</div>
            <div class="txt3">Shining</div>
        </div>
    </section>
    <!-- //section3 -->

    <section id="section4">
        <div class="text__inner">
            <div class="img img4"></div>
            <div class="txt1">Passion</div>
            <div class="txt2">Creative</div>
            <div class="txt3">Shining</div>
        </div>
    </section>
    <!-- //section4 -->

    <section id="section5">
        <div class="text__inner">
            <div class="img img5"></div>
            <div class="txt1">Passion</div>
            <div class="txt2">Creative</div>
            <div class="txt3">Shining</div>
        </div>
    </section>
    <!-- //section5 -->

    <section id="section6">
        <div class="text__inner">
            <div class="img img6"></div>
            <div class="txt1">Passion</div>
            <div class="txt2">Creative</div>
            <div class="txt3">Shining</div>
        </div>
    </section>
    <!-- //section6 -->
</main>

섹션별로 글씨색도 추가하겠습니다. 텍스트의 위치를 임의로 참고, 이미지도 절대값을 이용하여 임의로 설정하겠습니다. 여러분들은 섹션별로 위치를 다르게해서 작업하셔도 됩니다. 이미지는 unsplash3 경로를 그대로 가져와서 사용했습니다. 그럼 이제 기본 골격 설정은 끝난거 같습니다. 다음은 스크립트로 이동하겠습니다.

#section1 {
    background-color: #2c4855;
    color: #fff;
}
#section2 {
    background-color: #e3c4b8;
    color: #fff0f5;
}
#section3 {
    background-color: #947e75;
    color: #ffffff;
}
#section4 {
    background-color: #a16a0f;
    color: #E0B469;
}
#section5 {
    background-color: #354E5F;
    color: #8bb7d4;
}
#section6 {
    background-color: #c0621a;
    color: #ffc192;
}

/* text__inner */
.text__inner {
    text-align: center;
    font-size: 9vw;
    font-family: 'PPEiko-Thin';
    line-height: .81;
}
.text__inner .txt1 {
    margin-left: -40vw;
}
.text__inner .txt2 {
    position: relative;
    z-index: 10;
}
.text__inner .txt3 {
    margin-left: -30vw;
}
.text__inner .img {
    width: 30vw;
    height: 30vw;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    border-radius: 50%;
    position: absolute;
    right: 10vw;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
}
.text__inner .img img {
    width: 100%;
}
.text__inner .img.img1 {
    background-image: url(https://images.unsplash.com/photo-1672427045052-1dff001fb0b4?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2371&q=80);
}
.text__inner .img.img2 {
    background-image: url(https://images.unsplash.com/photo-1672667680124-6b9294abf071?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1166&q=80);
}
.text__inner .img.img3 {
    background-image: url(https://images.unsplash.com/photo-1672671225678-cb2588a961f7?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=688&q=80);
}
.text__inner .img.img4 {
    background-image: url(https://images.unsplash.com/photo-1672615086113-d7547be45622?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80);
}
.text__inner .img.img5 {
    background-image: url(https://images.unsplash.com/photo-1672627720536-e5c2843b1d7f?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1073&q=80);
}
.text__inner .img.img6 {
    background-image: url(https://images.unsplash.com/photo-1672278640012-49e959907a47?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80);
}

02. GSAP 코딩

우선 CDN을 연동하겠습니다.

<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@latest/bundled/lenis.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.3/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.3/ScrollTrigger.min.js"></script>

우선 CDN을 연동하겠습니다. Lenis2와 GSAP 기본 셋팅부터 하겠습니다. 이부분은 해당 깃에 보시면 설명이 자세히 나와있습니다.

gsap.registerPlugin(ScrollTrigger);

const lenis = new Lenis({
    duration: 1.2,
    easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
})

function raf(time) {
    lenis.raf(time)
    requestAnimationFrame(raf)
}
requestAnimationFrame(raf)

각 섹션을 선택자로 만듭니다. forEach를 이용하여 ScrollTrigger를 생성합니다. 각 섹션을 인식하고 각 섹션마다 스크로트리거를 인식할 수 있도록 했습니다. 트리거는 colorSection에 설정하고, 스크롤일 들어갔을 때, 나왔을 때 콜백함수를 설정했습니다.

각 섹션의 배경색과 글씨색은 data-값으로 설정했습니다. 이렇게 하면 작업하기 조금더 수월하겠죠! 🤪 data-bgcolor="#947e75" data-bgtext="#ffffff" 이런식으로 섹션마다 설정해줘서 색이 변경되게 만들었습니다.

그리고 스크롤이 된 다음에 다시 이전으로 가면 기존 색으로 변경되야 하기 때문에 prevBg, prevText 변수를 만들어서 기존 색을 다시 가져오도록 설정하여 onLeaveBack 함수에 설정하였습니다. 그리고 마지막으로 CSS 설정했던 배경색과 글씩색은 지워주시면 됩니다. 이거 깜박하고 안하시면 효과가 안보입니다.^^

const backColor = document.querySelectorAll("[data-bgcolor]");

backColor.forEach((colorSection, i) => {
    const prevBg = i === 0 ? "" : backColor[i - 1].dataset.bgcolor;
    const prevText = i === 0 ? "" : backColor[i - 1].dataset.bgtext;

    ScrollTrigger.create({
        trigger: colorSection,
        start: 'top 50%',
        end: 'bottom 5%',
        markers: false,
        onEnter: () => gsap.to("#main", {
            backgroundColor: colorSection.dataset.bgcolor,
            color: colorSection.dataset.bgtext,
        }),
        onLeaveBack: () => gsap.to("#main", {
            backgroundColor: prevBg,
            color: prevText
        })
    });
});

이렇게 해서 각 섹션별로 배경색과 텍스트 색이 변경되도록 하였습니다. 생각보다 어려운 부분이 없죠? 😅 이해가 안되는 부분은 댓글 주시고요! 하나씩 뜯어보면 별거 없다는 것을 느낄수 있을거에요! 그럼 오늘은 여기까지~ 수고하셨습니다.


HTML 레퍼런스

CSS 레퍼런스

자바스크립트 레퍼런스

사이트 레퍼런스


댓글0