ミッション:画面のランダムな場所に現れる的をクリックして、点数を稼ごう!
HTMLタブに下のコードを貼り付けてください。
<p id="score">0点</p>
<div id="target">🎯</div>
CSSタブに下のコードを貼り付けてください。
body {
margin: 0;
min-height: 100vh;
overflow: hidden;
}
#score {
font-size: 1.5rem;
padding: 10px;
}
#target {
position: fixed;
font-size: 60px;
cursor: pointer;
user-select: none;
}
JSタブに下のコードを貼り付けてください。
const target = document.querySelector('#target');
const score = document.querySelector('#score');
let count = 0;
target.style.left = Math.random() * (window.innerWidth - 80) + 'px';
target.style.top = Math.random() * (window.innerHeight - 80) + 'px';
target.addEventListener('click', function() {
count = count + 1;
score.textContent = count + '点';
target.style.left = Math.random() * (window.innerWidth - 80) + 'px';
target.style.top = Math.random() * (window.innerHeight - 80) + 'px';
});
的をクリックするたびにランダムな場所に移動し、点数が増えることを確認してください。
position: fixed でランダムな座標に置くtarget.style.left = Math.random() * (window.innerWidth - 80) + 'px';
target.style.top = Math.random() * (window.innerHeight - 80) + 'px';
「精霊を呼び出す場所」で event.clientX / Y を使ってクリックした座標に要素を置きました。今回は Math.random() を使ってランダムな座標を自分で計算しています。
window.innerWidth は画面の幅、window.innerHeight は画面の高さをピクセルで返します。- 80 しているのは的(60px)が画面からはみ出さないようにするためです。
target.addEventListener('click', function() {
// 点数を増やす
count = count + 1;
score.textContent = count + '点';
// 新しい場所に移動する
target.style.left = Math.random() * (window.innerWidth - 80) + 'px';
target.style.top = Math.random() * (window.innerHeight - 80) + 'px';
});
クリックされたあと style.left と style.top を新しいランダムな値で上書きすることで、的が別の場所に「移動」します。
同じコードが2箇所に出てくるのは(最初の配置とクリック後の移動)、「繰り返し」という共通のパターンになっています。
#target {
font-size: 60px; ← 大きくすると当てやすく、小さくすると難しくなる
}
サイズを変えたとき、JSの - 80 の値もサイズに合わせて調整してみましょう。
Math.random() と position: fixed を使っている