[자바스크립트] 3d 카드 만들기 Element.getBoundingClientRect() / mousemove event
인터렉티브 웹사이트 만들때 자주 쓰이는 요소
포트폴리오 웹사이트나 배너를 인터렉티브하게 만들고 싶을 때 어떻게 하면 좋을까?
Element.getBoundingClientRect()란?
자바스크립트에 내장된 함수이다.
아이템 요소의 크기와 뷰포트에서 상대적인 위치를 알려주는 DOMRect 객체를 반환한다
저 엘리먼트가 움직여줄 카드라고 생각해보자
내 마우스를 클릭할 때마다 마우스 클릭을 알고 그에 맞춰서 카드가 기울여지는 것이다
그럴려면 내 마우스 위치를 알아야겠지?
이 함수를 사용하면 왼쪽 여백 X좌표와 위쪽 여백 Y좌표
엘리먼트 width 값과 height 값을 구할 수 있다.
https://developer.mozilla.org/ko/docs/Web/API/Element/getBoundingClientRect
Element.getBoundingClientRect() - Web API | MDN
Element.getBoundingClientRect() 메서드는 엘리먼트의 크기와 뷰포트에 상대적인 위치 정보를 제공하는 DOMRect 객체를 반환합니다.
developer.mozilla.org
const container = document.getElementById('container')
const card = document.getElementById('card')
const gradation = document.getElementById('gradation')
let { x, y, width, height } = container.getBoundingClientRect()
그 다음에 필요한 요소는 마우스 무브 이벤트이다.
mousemove event 는?
내 마우스가 실제로 위치한 값을 e.clientX, e.clientY로 알려준다
mouseup, mousedown을 사용하여 그림판 처럼
마우스로 그림을 그리는 기능을 만들 수도 있다
예시는 아래와 같다
// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;
const myPics = document.getElementById("myPics");
const context = myPics.getContext("2d");
// event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.
// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener("mousedown", (e) => {
x = e.offsetX;
y = e.offsetY;
isDrawing = true;
});
myPics.addEventListener("mousemove", (e) => {
if (isDrawing) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
});
window.addEventListener("mouseup", (e) => {
if (isDrawing) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = 0;
y = 0;
isDrawing = false;
}
});
function drawLine(context, x1, y1, x2, y2) {
context.beginPath();
context.strokeStyle = "black";
context.lineWidth = 1;
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event
Element: mousemove event - Web APIs | MDN
The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.
developer.mozilla.org
카드 위에 위치한 마우스 좌표 구하기
function mouseMove(e) {
const left = e.clientX - x
const top = e.clientY - y
const centerX = left - width / 2
const centerY = top - height / 2
const degree = Math.sqrt(centerX**2 + centerY**2)
이렇게 해주면
마우스무브 함수에서 getBoundingClientRect에서 구한 x, y, width, height 값을 이용하여서
마우스 좌표값과 카드 중심점 위치, 원하는 기울기 각도를 구할 수 있다
container.addEventListener('mouseenter', () => {
container.addEventListener('mousemove', mouseMove)
})
container.addEventListener('mouseleave', () => {
container.removeEventListener('mousemove', mouseMove)
card.style.boxShadow = ''
card.style.transform = ''
light.style.backgroundImage = ''
})
card.style.transform = `
rotate3d(${-centerY / 100}, ${centerX / 100}, 0, ${degree / 12}deg)
`
gradation.style.backgroundImage = `
radial-gradient(circle at ${left}px ${top}px, #00000020, #ffffff00, #ffffff77)
`
}
이렇게 움직이는 걸 완성했다!!