amaranth.log
💻 개발

[인터랙티브 웹] 빛이 새어나오는 문 만들기

본 포스트는 인터랙티브 웹 개발 역량 향상을 위한 학습 차원에서 개발한 인터랙션을 기록하는 시리즈입니다. 사용한 기술 스택은 순수 HTML, CSS, JavaScript입니다.

서론

최근 머릿속에 번뜩 떠오른 인터랙션이 있어서 구현을 해봤는데, 결과물도 나름 만족스럽고 그 과정도 재미있었어서 구현 과정을 정리해보았다.
이 글을 읽는 분들도 차례대로 따라할 수 있게끔 글을 구성했다.

제작 과정1 - CSS로 형태 잡기

먼저 비스듬히 문이 열린 상태의 시각효과를 CSS로 구현해보겠다.
먼저 HTML 요소의 구조를 보자.
<div class="frame"> <div class="floor-light"></div> <div class="back-light"></div> <div class="door"></div> </div>
frame은 문틀, floor-light는 바닥에 비치는 빛줄기, back-light는 문 뒤로 보이는 빛, door는 문이다.
먼저 frame에 기본적인 스타일을 적용한다.
.frame { outline: 4px solid aqua; width: 100px; height: 100px; }
notion image
비스듬히 바라본 것 같은 효과를 주기 위해, CSS의 transform 속성으로 skew 함수를 20°만큼 적용한다.
.frame { outline: 4px solid aqua; width: 100px; height: 100px; transform: skewY(-20deg); }
notion image
💡
skew()
요소를 기울여 변형하는 2D 변환 함수이다.
skew()는 요소의 x축과 y축 방향으로 기울기를 적용하는데, 기본 문법은 다음과 같다.
transform: skew(ax, ay);
  • ax: x축 기준의 기울기
  • ay: y축 기준의 기울기
*단위는 deg, rad, grad, turn
예를 들어 다음과 같이 속성을 지정하면 요소는 x축 방향으로 20°, y축 방향으로 10°만큼 기울어진다.
transform: skew(20deg, 10deg);
한 축만을 기준으로 변형을 적용하고 싶다면 skewX(ax), skewY(ay)를 사용할 수도 있다.
notion image
기하학적으로 봤을 때, skew는 수학적으로 shear transformation이다.
skewX(a)는 다음과 같은 변환을 의미한다.
x' = x + y * tan(a) y' = y
notion image
그리고 door의 스타일을 적용하고, 비스듬히 열린 것처럼 보이도록 translate()를 적용한다.(이후 자바스크립트로 인터랙션을 구현할 때 제거할 것이다)
.door { background: black; border: 1px solid aqua; width: 100px; height: 100px; transform: translate(-20px); }
notion image
그 다음 back-light의 스타일을 적용한다. 이 때 door와 back-light가 겹쳐질 수 있도록, position 속성과 z-index 속성을 적절히 설정해준다.
.frame { position: relative; outline: 4px solid aqua; transform: skewY(-20deg); width: 100px; height: 100px; } .door { position: absolute; top: 0; right: 0; z-index: 3; background: black; border: 1px solid aqua; width: 100px; height: 100px; transform: translate(-20px); } .back-light { position: absolute; inset: 0; z-index: 1; background: yellow; }
notion image
그 다음으로 바닥에 비추는 빛줄기를 구현해야 한다.
먼저 위치를 100px(=frame의 높이)만큼 아래로 이동시키고 크기와 배경 색상을 지정해본다.
.floor-light { position: absolute; width: 100px; height: 100px; background: yellow; transform: translateY(100px); }
notion image
바닥과 벽 간의 공간감을 주기 위해, frame의 x축 방향(표준 x축 기준 20° 방향)으로 floor-light를 비틀어준다.
.floor-light { position: absolute; width: 100px; height: 100px; background: yellow; transform: translateY(100px) skewX(40deg); }
notion image
현재 transform-origin이 default 값인 center로 되어 있기 때문에, floor-light의 정 중앙을 기준으로 skew()가 적용되어 frame의 기준면(오른쪽 면)과 떨어져 보인다. 이를 해결하기 위해 transform 변환의 기준 점을 floor-light 요소의 상단으로 설정한다.
.floor-light { position: absolute; width: 100px; height: 100px; background: yellow; transform-origin: top; transform: translateY(100px) skewX(40deg); }
notion image
💡
transform-origin
transform이 적용될 기준점을 정의하는 CSS 요소.
transform-origin: x y z;의 형태로 사용하며, 주로 x와 y만 지정한다.
transform-origin: left top; transform-origin: 0 0; transform-origin: 100% 50%;
예시) transform: rotate(45deg)
transform-origin에 따라 다음과 같이 변환 결과가 달라진다.
notion image
이제 빛줄기의 모양을 만들어야 하는데, 빛줄기의 윗면 너비는 문 틈의 너비와 같아야 하고 광원에서 멀어질 수록 점점 넓어지는 모양새가 되어야 한다. 문이 완전히 열렸을 때를 기준으로 윗면 너비와 아랫면 너비가 1:3 비율이면 좋겠다고 생각했다.
notion image
그래서 먼저 floor-light의 기본 높이와 너비를 3배씩 늘려주었다.
.floor-light { position: absolute; width: 300px; height: 300px; background: yellow; transform-origin: top; transform: translateY(100px) skewX(40deg); }
notion image
빛줄기 모양은 대칭되도록 표현하고 싶다. 문이 빛줄기 요소의 중앙으로 오게끔 translate로 빛줄기 요소를 -100px만큼 이동시켜준다.
.floor-light { position: absolute; width: 300px; height: 300px; background: yellow; transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); }
notion image
윗면 너비는 빛줄기의 문 틈 너비, 아랫면 너비는 윗면의 3배가 되게끔 요소를 잘라준다. 이 때, clip-path의 poligon() 함수를 사용한다.
💡
clip-path
요소의 보이는 영역을 특정 도형으로 잘라내는 CSS 속성
요소 자체를 변형하는 것이 아니라, 마스킹처럼 렌더링되는 영역을 제한한다.
속성 값으로 circle(), ellipse(), inset(), polygon() 등이 있다.
  • circle(<radius> at <position>): 반지름 값을 기준으로 하는 원형으로 잘라낸다.
  • ellipse(<rx> <ry> at <position>): 가로 반지름과 세로 반지름을 기준으로 하는 타원을 잘라낸다.
  • inset(top right bottom left): 사각형을 안쪽으로 잘라낸다.
  • polygon(x1 y1, x2 y2, …, xn yn): n개의 변을 가진 임의의 다각형을 만들 수 있다.
clip-path에 지정할 좌표 값은 다음과 같이 계산했다.
180px 0, 160px 300px, 220px 300px, 200px 0
notion image
.floor-light { position: absolute; width: 300px; height: 300px; background: yellow; transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); clip-path: polygon(180px 0, 170px 300px, 210px 300px, 200px 0); }
notion image
이 뒤에 인터랙션을 넣는 과정에서 ‘문이 열린 정도’는 변수가 될 것이기 때문에, 이를 변수 a로 두고 일반화하면 다음과 같이 좌표를 표현할 수 있다.
(200-a)px 0, (200-2*a)px 300px, (200+a)px 300px, 200px 0
notion image
이제 광원에서 멀어질수록 floor-light가 어두워지는 것처럼 그라디언트를 입혀보자. 빛줄기의 모양은 y축을 기준으로 항상 대칭이므로 그라디언트 방향을 0으로 설정했다.
.floor-light { position: absolute; width: 300px; height: 300px; background: yellow; background: linear-gradient(0, transparent 30%, #ffff0033 60%, yellow 120%); transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); clip-path: polygon(180px 0, 170px 300px, 210px 300px, 200px 0); }
notion image
여담으로 빛줄기가 광원보다 밝을 수는 없기 때문에 이 부분을 고증하고 싶어 노란 색 그라디언트 지점을 120%로 설정했다.

제작 과정2 - JavaScript로 문이 열리는 인터랙션 넣기

이제 사용자가 문을 드래그해서 열고 닫을 수 있도록 인터랙션을 구현해보자.
먼저 UI 구현을 위해 door 요소에 임시로 적용했던 translate()를 제거해주자.
.door { position: absolute; top: 0; right: 0; z-index: 3; background: black; border: 1px solid aqua; width: 100px; height: 100px; transform: translate(-20px); }
그리고 사용자가 door 요소를 드래그했을 때, 처음 door 요소를 클릭한 시점의 문의 위치를 기준으로 현재 마우스의 위치가 얼마나 멀리 떨어져있는지를 구해야 한다. door는 자신의 좌표계 내에서 x축 방향(좌우)으로만 움직이므로 x좌표의 차이를 구하면 될 것이다.
const door = document.querySelector(".door"); let isDragging = false; let startOpenAmount = 0; // 드래그를 시작했을 때 문이 열린 정도(px 단위) let savedOpenAmount = 0; // 현재 문이 열린 정도(px 단위) let startX = 0; // 드래그를 시작했을 때 마우스의 x 좌표(px 단위) door.addEventListener("pointerdown", (event) => { isDragging = true; startX = event.clientX; startOpenAmount = savedOpenAmount; }); function initializeDrag() { isDragging = false; } document.addEventListener("mouseleave", initializeDrag); door.addEventListener("pointerup", initializeDrag); door.addEventListener("pointermove", (event) => { if (!isDragging) return; const dx = startX - event.clientX; // 이번 드래그 이벤트 동안 문이 열린 정도 savedOpenAmount = startOpenAmount + dx; // 현재 문이 열린 정도 door.style.transform = `translateX(${-savedOpenAmount}px)`; // 문이 열리는 방향은 왼쪽이므로 translateX 값의 부호가 -(마이너스)가 되어야 문이 열린다. });
notion image
지금은 문이 frame을 벗어나기도 하고, 열려야 할 방향의 반대 방향으로도 문이 열리고 있다. translateX가 항상 -100(frame의 너비)과 0 사이의 값이 되도록 savedOpenAmount를 보정한다.
... door.addEventListener("pointermove", (event) => { if (!isDragging) return; const dx = startX - event.clientX; savedOpenAmount = startOpenAmount + dx; const effectiveOpenAmount = Math.min(100, Math.max(0, savedOpenAmount)) door.style.transform = `translateX(${-effectiveOpenAmount}px)`; });
notion image
이제 바닥의 빛줄기도 문이 열린 정도에 따라 동적으로 모양이 바뀌게 해보자.
먼저 css에서 floor-light의 기본 clip-path 속성을 초기화하자.
.floor-light { position: absolute; width: 300px; height: 300px; background: linear-gradient(0, transparent 30%, #ffff0033 60%, yellow 120%); transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); clip-path: polygon(200px 0, 200px 300px, 200px 300px, 200px 0); }
그리고 door 요소를 드래그할 때마다, floor-light의 clip-path 속성을 업데이트한다.
const DOOR_END_POINT = 200; const door = document.querySelector(".door"); const floorLight = document.querySelector(".floor-light"); ... door.addEventListener("pointermove", (event) => { if (!isDragging) return; const dx = startX - event.clientX; savedOpenAmount = startOpenAmount + dx; effectiveOpenAmount = Math.min(100, Math.max(0, savedOpenAmount)); door.style.transform = `translateX(${-effectiveOpenAmount}px)`; floorLight.style.clipPath = `polygon(${DOOR_END_POINT - effectiveOpenAmount}px 0, ${DOOR_END_POINT - 2 * effectiveOpenAmount}px 300px, ${DOOR_END_POINT + effectiveOpenAmount}px 300px, ${DOOR_END_POINT}px 0)`; });
notion image
이제 여기에 이스터에그를 넣어보자.

제작 과정3 - 이스터에그 만들기(그림자 만들기)

이제 문을 열었을 때 랜덤한 확률로 사람 형상의 요소와 그 그림자가 나타나게 해보자.
일단 개발 편의성을 위해 처음부터 문이 열린 상태가 되게끔 translate()를 적용하고, 빛줄기의 클리핑과 그라디언트 효과도 주석처리한다.
... .door { position: absolute; top: 0; right: 0; z-index: 3; background: black; border: 1px solid aqua; width: 100px; height: 100px; transform: translateX(-100px); } ... .floorlight { position: absolute; width: 300px; height: 300px; background: yellow; /* background: linear-gradient(0, transparent 30%, #ffff0033 60%, yellow 120%); */ transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); /* clip-path: polygon(200px 0, 200px 300px, 200px 300px, 200px 0); */ }
notion image
그리고 이스터에그와 관련된 html 요소를 추가하자.
<svg width="0" height="0" viewBox="0 0 30 50" fill="none"> <clipPath id="man"> <path d="M15 0C14.0054 0 13.0516 0.501699 12.3484 1.39473C11.6451 2.28776 11.25 3.49897 11.25 4.7619C11.25 7.40476 12.9188 9.52381 15 9.52381C17.0812 9.52381 18.75 7.40476 18.75 4.7619C18.75 3.49897 18.3549 2.28776 17.6516 1.39473C16.9484 0.501699 15.9946 0 15 0ZM11.25 11.9048C10.7437 11.9048 10.3125 12.1667 9.95625 12.5714H9.9375L0 25.2143L2.6625 28.5714L9.375 20.0238V50H13.125V33.3333H16.875V50H20.625V20.0238L27.3375 28.5714L30 25.2143L20.0625 12.5714C19.6875 12.1667 19.2563 11.9048 18.75 11.9048" /> </clipPath> </svg> <div class="frame"> <div class="floor-light"> <div class="man-shadow"></div> </div> <div class="back-light"></div> <div class="hidden-man"></div> <div class="door"></div> </div>
svg 리소스는 피그마에서 가져왔고, 너비와 높이는 각각 30px, 50px로 정했다.
notion image
그리고 문에 서있는 사람의 형상(hidden-man)을 back-light 요소와 door 요소 사이에 두고(z-index를 적절히 설정), 문 중앙에 위치하도록 position을 적절히 설정해준다. 그리고 clip-path 속성을 앞서 추가했던 <clipPath>와 매핑해 요소를 사람 형상으로 깎아준다.
.hidden-man { position: absolute; bottom: 0; left: 35px; z-index: 2; background: black; width: 30px; height: 50px; clip-path: url("#man"); }
notion image
다음은 그림자의 스타일을 설정해준다. 마찬가지로 요소의 위치를 적절히 설정해주고 모양을 사람 형상으로 깎은 후, 그림자는 hidden-man에 비해 상하가 반전된 형상이므로 transform: scaleY(-1)로 요소를 상하반전시켜준다.
.man-shadow { position: absolute; right: 135px; top: 0px; width: 30px; height: 50px; background: black; transform: scaleY(-1); clip-path: url(#man); }
notion image
다음으로, 그림자의 끝을 빛줄기처럼 넓게 퍼지게 만들고 싶다. 여기에선 transform 속성의 perspective()와 rotateX()를 활용한다.
💡
perspective()와 rotate()
rotateX(), rotateY, rotateZ()(=rotate())는 각각 요소의 x축, y축, z축을 기준으로 요소를 회전시킨다.
요소를 3차원 좌표상에서 회전시킨 것과 같은 효과이기 때문에, rotateX()와 rotateY()를 사용하면 2D상에서 도형이 찌그러진 것처럼 보인다.
notion image
perspective()는 rotate와 같은 3D 변환에서 깊이를 표현하기 위한 투영 거리를 설정하는 함수이다.
이 투영 거리란 관찰자와 화면 사이의 거리라고 할 수 있는데 이 값이 작을수록 원근 효과가 강하고, 클수록 원근 효과가 약하다.
*카메라와의 거리가 가까울 수록, 같은 거리를 움직여도 더 많이 움직인 것처럼 보이는 것과 같은 원리
*3D 변환을 적용한 후 원근 투영을 시켜야 하므로 변환 후에 perspective() 함수를 배치시켜야 한다.
X축을 기준으로 40°만큼 회전시키고, 카메라와의 거리는 50px로 설정해준다. 이 때, 그림자의 발 부분은 실물(hidden-man)의 발과 같은 크기여야 하므로 transform-origin을 bottom으로 설정한다. 근데 이렇게 하면 scaleY가 적용되면서 그림자가 문 뒤편으로 넘어가버리기 때문에 위치 정의를 top:0에서 bottom:300px로 수정해 보완한다.
.man-shadow { position: absolute; right: 135px; top: 0px; bottom: 300px; width: 30px; height: 50px; background: black; transform-origin: bottom; transform: perspective(50px) rotateX(40deg) scaleY(-1); clip-path: url(#man); }
notion image
그리고 그라데이션을 적용해준다.
.man-shadow { position: absolute; right: 135px; bottom: 300px; width: 30px; height: 50px; background: black; background: linear-gradient(0, black -40%, #000033 20%, transparent 100%); transform-origin: bottom; transform: perspective(50px) rotateX(40deg) scaleY(-1); clip-path: url(#man); }
notion image
다시 문을 닫아주고 빛줄기도 없애준 뒤, 이스터에그 요소(hidden-man, man-shadow)의 기본 display 속성을 none으로 설정해준다.
... .door { position: absolute; top: 0; right: 0; z-index: 3; background: black; border: 1px solid aqua; width: 100px; height: 100px; transform: translateX(-100px); } ... .floor-light { position: absolute; width: 300px; height: 300px; background: yellow; background: linear-gradient(0, transparent 30%, #ffff0033 60%, yellow 120%); transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); clip-path: polygon(200px 0, 200px 300px, 200px 300px, 200px 0); } .hidden-man { position: absolute; bottom: 0; left: 35px; z-index: 2; background: black; width: 30px; height: 50px; clip-path: url("#man"); display: none; } .man-shadow { position: absolute; right: 135px; bottom: 300px; width: 30px; height: 50px; background: linear-gradient(0, black -40%, #000033 20%, transparent 100%); transform-origin: bottom; transform: perspective(50px) rotateX(40deg) scaleY(-1); clip-path: url(#man); display: none; }
이제 자바스크립트 코드로 와서, 문이 닫힐 때마다 랜덤한 확률로 이스터에그 요소가 나타나게 해보자.
... const hiddenMan = document.querySelector(".hidden-man"); const manShadow = document.querySelector(".man-shadow"); ... door.addEventListener("pointermove", (event) => { if (!isDragging) return; const dx = startX - event.clientX; // 이번 드래그 이벤트 동안 문이 열린 정도 savedOpenAmount = startOpenAmount + dx; // 현재 문이 열린 정도 if (savedOpenAmount <= 0) { if (3 * Math.random() > 2) { // 1/3 확률로 문 뒤에 사람이 나타난다. hiddenMan.style.display = "block"; manShadow.style.display = "block"; } else { hiddenMan.style.display = "none"; manShadow.style.display = "none"; } } const effectiveOpenAmount = Math.min(100, Math.max(0, savedOpenAmount)); door.style.transform = `translateX(${-effectiveOpenAmount}px)`; floorLight.style.clipPath = `polygon(${DOOR_END_POINT - effectiveOpenAmount}px 0, ${DOOR_END_POINT - 2 * effectiveOpenAmount}px 300px, ${DOOR_END_POINT + effectiveOpenAmount}px 300px, ${DOOR_END_POINT}px 0)`; });
notion image

최종 코드

html
<svg width="0" height="0" viewBox="0 0 30 50" fill="none"> <clipPath id="man"> <path d="M15 0C14.0054 0 13.0516 0.501699 12.3484 1.39473C11.6451 2.28776 11.25 3.49897 11.25 4.7619C11.25 7.40476 12.9188 9.52381 15 9.52381C17.0812 9.52381 18.75 7.40476 18.75 4.7619C18.75 3.49897 18.3549 2.28776 17.6516 1.39473C16.9484 0.501699 15.9946 0 15 0ZM11.25 11.9048C10.7437 11.9048 10.3125 12.1667 9.95625 12.5714H9.9375L0 25.2143L2.6625 28.5714L9.375 20.0238V50H13.125V33.3333H16.875V50H20.625V20.0238L27.3375 28.5714L30 25.2143L20.0625 12.5714C19.6875 12.1667 19.2563 11.9048 18.75 11.9048" /> </clipPath> </svg> <div class="frame"> <div class="floor-light"> <div class="man-shadow"></div> </div> <div class="back-light"></div> <div class="hidden-man"></div> <div class="door"></div> </div>
css
.frame { position: relative; outline: 4px solid aqua; transform: skewY(-20deg); width: 100px; height: 100px; } .door { position: absolute; top: 0; right: 0; z-index: 3; background: black; border: 1px solid aqua; width: 100px; height: 100px; } .back-light { position: absolute; inset: 0; z-index: 1; background: yellow; } .floor-light { position: absolute; width: 300px; height: 300px; background: linear-gradient(0, transparent 30%, #ffff0033 60%, yellow 120%); transform-origin: top; transform: translate(-100px, 100px) skewX(40deg); clip-path: polygon(200px 0, 200px 300px, 200px 300px, 200px 0); } .hidden-man { position: absolute; bottom: 0; left: 35px; z-index: 2; background: black; width: 30px; height: 50px; clip-path: url("#man"); display: none; } .man-shadow { position: absolute; right: 135px; bottom: 300px; width: 30px; height: 50px; background: linear-gradient(0, black -40%, #000033 20%, transparent 100%); transform-origin: bottom; transform: perspective(50px) rotateX(40deg) scaleY(-1); clip-path: url(#man); display: none; }
javascript
const DOOR_END_POINT = 200; const door = document.querySelector(".door"); const floorLight = document.querySelector(".floorlight"); const hiddenMan = document.querySelector(".hidden-man"); const manShadow = document.querySelector(".man-shadow"); let isDragging = false; let startOpenAmount = 0; // 드래그를 시작했을 때 문이 열린 정도(px 단위) let savedOpenAmount = 0; // 현재 문이 열린 정도(px 단위) let startX = 0; // 드래그를 시작했을 때 마우스의 x 좌표(px 단위) door.addEventListener("pointerdown", (event) => { isDragging = true; startX = event.clientX; startOpenAmount = savedOpenAmount; }); function initializeDrag() { isDragging = false; } document.addEventListener("mouseleave", initializeDrag); door.addEventListener("pointerup", initializeDrag); door.addEventListener("pointermove", (event) => { if (!isDragging) return; const dx = startX - event.clientX; // 이번 드래그 이벤트 동안 문이 열린 정도 savedOpenAmount = startOpenAmount + dx; // 현재 문이 열린 정도 if (savedOpenAmount <= 0) { if (3 * Math.random() > 2) { hiddenMan.style.display = "block"; manShadow.style.display = "block"; } else { hiddenMan.style.display = "none"; manShadow.style.display = "none"; } } const effectiveOpenAmount = Math.min(100, Math.max(0, savedOpenAmount)); door.style.transform = `translateX(${-effectiveOpenAmount}px)`; floorLight.style.clipPath = `polygon(${DOOR_END_POINT - effectiveOpenAmount}px 0, ${DOOR_END_POINT - 2 * effectiveOpenAmount}px 300px, ${DOOR_END_POINT + effectiveOpenAmount}px 300px, ${DOOR_END_POINT}px 0)`; });