Nút nam châm
Chuột lại gần thì nút bị hút theo. Rời ra thì bật về như lò xo.
Đang tải demo…
Cách hoạt động
- 1.Tính khoảng cách từ chuột tới tâm nút, dịch nút theo 35% khoảng cách đó.
- 2.Chữ bên trong dịch ít hơn vỏ nút. Hai lớp lệch nhau nên nhìn có chiều sâu.
- 3.Chuột rời đi thì dùng elastic.out để nút bật về.
Code chính
const xTo = gsap.quickTo(btn, "x", { duration: 0.5, ease: "power3" });
const yTo = gsap.quickTo(btn, "y", { duration: 0.5, ease: "power3" });
const lxTo = gsap.quickTo(label, "x", { duration: 0.5, ease: "power3" });
const lyTo = gsap.quickTo(label, "y", { duration: 0.5, ease: "power3" });
btn.addEventListener("pointermove", (e) => {
const r = btn.getBoundingClientRect();
const dx = e.clientX - (r.left + r.width / 2);
const dy = e.clientY - (r.top + r.height / 2);
xTo(dx * 0.35); yTo(dy * 0.35);
lxTo(dx * 0.18); lyTo(dy * 0.18);
});
btn.addEventListener("pointerleave", () => {
gsap.to([btn, label], { x: 0, y: 0, duration: 1, ease: "elastic.out(1, 0.35)" });
});