반응형
기본 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouse Shadow</title>
</head>
<body>
<div class="hero">
<h1 contenteditable>🔥WOAH!</h1>
</div>
<style>
html {
color:black;
font-family: sans-serif;
}
body {
margin: 0;
}
.hero {
min-height: 100vh;
display:flex;
justify-content: center;
align-items: center;
color:black;
}
h1 {
text-shadow: 10px 10px 0 rgba(0,0,0,1);
font-size: 100px;
}
</style>
<script>
const hero = document.querySelector('.hero');
const text = hero.querySelector('h1');
const walk = 500;
</script>
</body>
</html>
목표
마우스의 이동에 따라 가운데 적힌 글씨에 대한 4개의 그림자가 같이 움직이게 만들어보자
코드 분석
function shadow(e) {
const { offsetWidth: width, offsetHeight: height } = hero;
let { offsetX: x, offsetY: y } = e;
if (this !== e.target) {
x = x + e.target.offsetLeft;
y = y + e.target.offsetTop;
}
const xWalk = Math.round((x / width * walk) - (walk / 2));
const yWalk = Math.round((y / height * walk) - (walk / 2));
내용을 살펴보면 hero
의 width
와 height
값을 지정해주었고e
의 x축, y축 좌표를 지정해둔다.
그 다음에는 body
에 현재 부모에 해당하는 hero
와 그 아래의 자식에 해당하는 h1
부분이 있기 때문에 서로 다른 offset
값을 가지게 되기 때문에 if
문을 통해 값을 맞춰주는 것이다.
text.style.textShadow = `
${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),
${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),
${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),
${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)
`;
}
hero.addEventListener('mousemove', shadow);
나머지 내용은 그림자 역할을 하는 내용들을 추가해주고, 이벤트를 만들어 준 것이다.
마무리
이번 회차도 대부분 이전 회차들에서 한번씩은 다룬 내용들로 구성이 되어있어서 크게 어렵지 않았다.
끝.
반응형
'개발 > JavaScript 30' 카테고리의 다른 글
18. Adding Up Times with Reduce (0) | 2017.04.24 |
---|---|
17. Sort Without Articles (0) | 2017.04.22 |
15. LocalStorage (0) | 2017.04.22 |
14. JavaScript References VS Copying (0) | 2017.04.19 |
13. Slide in on Scroll (0) | 2017.04.19 |