Javascript 30 - Gün 16

Projenin demosu : Demo

Başlangıç dosyalarını bulabileceğiniz repom: js-30 | github

Bugün CSS’deki text-shadow özelliğini JS ile dinamik hale getirip farenin hareketine göre gölgenin konumunu değiştirdiğimiz basit bir proje geliştiriyoruz. Bu projede konumu belirlerken sorun yaratacak olan bir durum var:

  • hero elementinde fare hareketini izliyoruz ancak e.target yani olayın gerçekleştiği element eğer içerideki h1 olursa fare konumları yanlış geliyor. Bu durumu düzeltmek içinde fonksiyon içerisinde olayın gerçekleştiği elementin hero olup olmadığını kontrol edip değerleri ona göre belirliyoruz.

Çözümüm

 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4<meta charset="UTF-8">
 5<title>Mouse Shadow</title>
 6<link rel="icon" href="https://fav.farm/✅" />
 7</head>
 8<body>
 9
10<div class="hero">
11  <h1>Hello!</h1>
12</div>
13
14<style>
15  html {
16    color: black;
17    font-family: sans-serif;
18  }
19
20  body {
21    margin: 0;
22  }
23
24  .hero {
25    min-height: 100vh;
26    display: flex;
27    justify-content: center;
28    align-items: center;
29    color: black;
30  }
31
32  h1 {
33    text-shadow: 10px 10px 7px rgba(0, 0, 0, 0.2);
34    font-size: 100px;
35  }
36</style>
37
38<script>
39const hero = document.querySelector('.hero');
40const text = hero.querySelector('h1');
41const move = 50; // 50px
42
43function shadow(e) {
44  const {offsetWidth: width, offsetHeight: height} = hero;
45  let {offsetX: x, offsetY: y} = e;
46
47  // üzerine fareyle gelinen element hedefimiz olan hero elementi değilde içerisindeki
48  // h1 elementi olursa x,y değerlerine h1in offset değerlerini ekliyoruz böylece
49  // gölgenin pozisyonu doğru olmuş olacaktır.
50  if (this !== e.target) {
51    x = x + e.target.offsetLeft;
52    y = y + e.target.offsetTop;
53  }
54
55  // text-shadow özelliğinin konumunu hesaplayalım 
56  const xMove = Math.round((x / width * move) - (move / 2));
57  const yMove = Math.round((y / height * move) - (move / 2));
58
59  text.style.textShadow = `
60  ${xMove}px ${yMove}px 7px rgba(0,0,0,0.2)`;
61
62}
63
64hero.addEventListener('mousemove', shadow);
65</script>
66</body>
67
68</html>