Animate to Target
function box(x, y, col = 'red', cursor){
const box = document.body.appendChild(
document.createElement`div`
)
box.classList.add(col + '-box')
Object.assign(box.style, {
position: 'absolute',
left: `${x}%`,
top: `${y}%`,
width: '30px',
height: '30px',
background: col,
cursor: cursor || 'pointer',
color: 'white'
})
return box
}
const NUM = 10;
for (let i = 0; i < NUM; i++)
box(
Math.random() * 100,
Math.random() * 100)
let destX = destY = x = y = 0;
const blue = box(destX, destY, 'blue', 'default')
const info = box(0, 30, 'gray')
info.innerHTML = 'click the red boxes'
Object.assign(info.style, {
width: '100%',
padding: '.5em',
fontFamily: 'sans-serif'
})
document.addEventListener('click', e => {
const curr = e.target
if (curr.classList.contains('red-box')) {
destX = curr.offsetLeft
destY = curr.offsetTop
curr.style.background = 'black'
setTimeout(() => curr.style.background = 'red', 700)
if (info.parentNode != null) {
info.parentNode.removeChild(info);
}
}
})
function loop() {
x += (destX - x) / 12
y += (destY - y) / 12
blue.style.transform = `translate3d(${x}px, ${y}px, 0)`
requestAnimationFrame(loop)
}
loop()
Click a red box, watch the blue box animate…