zenn_waapi_demo04
by 6242ea4
HTML
<div class="stage">
<div class="box"></div>
クリックした位置まで動きます
</div>
CSS
body {
margin: 0;
}
.stage {
position: relative;
height: 100vh;
min-height: 240px;
display: grid;
place-items: center;
color: gray;
user-select: none;
}
.box {
position: absolute;
top: 0;
left: 0;
width: 48px;
height: 48px;
background: tomato;
}
JavaScript
const stage = document.querySelector('.stage');
const box = document.querySelector('.box');
stage.addEventListener('click', (e) => {
// クリックした位置から移動先を計算する
const rect = stage.getBoundingClientRect();
const x = e.clientX - rect.left - box.offsetWidth / 2;
const y = e.clientY - rect.top - box.offsetHeight / 2;
// キーフレームが 1 つなので、現在の位置から動き始める
box.animate(
{ transform: `translate(${x}px, ${y}px)` },
{ duration: 400, easing: 'cubic-bezier(0,1,0,1)', fill: 'forwards' }
);
});