Магнитная кнопка
Кнопка и поле точек, которые тянутся к курсору. Клик пускает по полю волну.
- Кнопки и переключатели
- Бесплатно
- canvas
- particles
- spring
- Добавлен 12 сентября 2026
<style>
.field { position: relative; width: min(560px, 92vw); height: min(360px, 52vh); }
.field canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
.magnet {
position: absolute; left: 50%; top: 50%; padding: 16px 30px; border: 0; border-radius: 999px;
background: linear-gradient(180deg, #F7F9FC 0%, #DFE4EB 100%); color: #111519;
font: 650 17px/1 system-ui, sans-serif; letter-spacing: -.015em; cursor: pointer; white-space: nowrap;
box-shadow: 0 1px 0 rgba(255,255,255,.7) inset, 0 18px 34px -16px rgba(0,0,0,.75);
will-change: transform;
}
.hint { position: fixed; bottom: 24px; left: 0; right: 0; text-align: center; color: #5C6472; font-size: 13px; }
</style>
<div class="field" id="field">
<canvas id="dots"></canvas>
<button class="magnet" id="btn">Get started</button>
</div>
<script>
// ── the same numbers as in the video
const RADIUS = 140, PULL = 0.35;
const BTN_PULL = 0.62, WAVE = 0.9, STEP = 26;
const field = document.getElementById('field');
const cv = document.getElementById('dots'), ctx = cv.getContext('2d');
const btn = document.getElementById('btn');
let W = 0, H = 0, dots = [];
let mx = -9999, my = -9999; // cursor in field coordinates
let clickAt = null, clickT = 0;
function layout() {
const r = field.getBoundingClientRect();
W = r.width; H = r.height;
cv.width = W * devicePixelRatio; cv.height = H * devicePixelRatio;
ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);
dots = [];
for (let y = STEP / 2; y < H; y += STEP)
for (let x = STEP / 2; x < W; x += STEP) dots.push({ x, y });
}
layout();
addEventListener('resize', layout);
field.addEventListener('pointermove', e => {
const r = field.getBoundingClientRect();
mx = e.clientX - r.left; my = e.clientY - r.top;
});
field.addEventListener('pointerleave', () => { mx = my = -9999; });
btn.addEventListener('click', () => {
const r = field.getBoundingClientRect(), b = btn.getBoundingClientRect();
clickAt = [b.left - r.left + b.width / 2, b.top - r.top + b.height / 2];
clickT = performance.now();
});
function frame(now) {
// the button is pulled by the same formula as the dots, just harder
const bx = W / 2, by = H / 2;
const bdx = mx - bx, bdy = my - by, br = Math.hypot(bdx, bdy);
const bk = Math.max(0, 1 - br / (RADIUS * 1.9)) * BTN_PULL;
btn.style.transform = `translate(calc(-50% + ${(bdx * bk).toFixed(1)}px), calc(-50% + ${(bdy * bk).toFixed(1)}px))`;
// click wave, a ring spreads out and fades
const since = clickAt ? (now - clickT) / 1000 : -1;
const wave = since >= 0 && since < 2.4 ? Math.exp(-since * WAVE) : 0;
const waveR = since >= 0 ? since * 190 : -1;
ctx.clearRect(0, 0, W, H);
for (const d of dots) {
const dx = mx - d.x, dy = my - d.y;
const r = Math.hypot(dx, dy);
const k = Math.max(0, 1 - r / RADIUS);
let ox = dx * k * PULL, oy = dy * k * PULL;
if (wave > 0 && clickAt) {
const rb = Math.hypot(d.x - clickAt[0], d.y - clickAt[1]);
const gap = Math.abs(rb - waveR);
if (gap < 84) {
const push = Math.cos(gap / 84 * Math.PI / 2) * wave * 26;
const len = Math.max(rb, .001);
ox += (d.x - clickAt[0]) / len * push;
oy += (d.y - clickAt[1]) / len * push;
}
}
const near = Math.min(1, k * 1.6);
const rad = 1.6 + near * 2.6;
const px = Math.min(Math.max(d.x + ox, rad), W - rad);
const py = Math.min(Math.max(d.y + oy, rad), H - rad);
ctx.beginPath();
ctx.arc(px, py, rad, 0, 6.2832);
ctx.fillStyle = `rgba(${104 + near * 96 | 0},${116 + near * 108 | 0},${138 + near * 117 | 0},${(.40 + near * .58).toFixed(3)})`;
ctx.fill();
}
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
Поведите курсором рядом с кнопкой и нажмите на неё.
Что можно поменять
Поменяйте число, сохраните файл и обновите страницу, разница будет видна сразу.
RADIUS140Как далеко достаёт притяжение, в пикселях. При 300 курсор чувствуется с половины экрана.
PULL0.35Насколько сдвигаются точки. При 0.8 они почти прилипают к курсору.
Как поставить на свой сайт
Поставьте на первый экран. Поменяйте текст кнопки и оберните её в ссылку, если она должна куда-то вести.
Комментарии в коде на английском, так файл понятен любому разработчику.
CSS
Вставьте в свой файл стилей или в тег <style> внутри <head>.
.field { position: relative; width: min(560px, 92vw); height: min(360px, 52vh); } .field canvas { position: absolute; inset: 0; width: 100%; height: 100%; } .magnet { position: absolute; left: 50%; top: 50%; padding: 16px 30px; border: 0; border-radius: 999px; background: linear-gradient(180deg, #F7F9FC 0%, #DFE4EB 100%); color: #111519; font: 650 17px/1 system-ui, sans-serif; letter-spacing: -.015em; cursor: pointer; white-space: nowrap; box-shadow: 0 1px 0 rgba(255,255,255,.7) inset, 0 18px 34px -16px rgba(0,0,0,.75); will-change: transform; } .hint { position: fixed; bottom: 24px; left: 0; right: 0; text-align: center; color: #5C6472; font-size: 13px; }HTML
Поставьте в то место страницы, где должен быть эффект.
<div class="field" id="field"> <canvas id="dots"></canvas> <button class="magnet" id="btn">Get started</button> </div>JavaScript
Вставьте перед закрывающим тегом </body>, внутри <script></script>.
// ── the same numbers as in the video const RADIUS = 140, PULL = 0.35; const BTN_PULL = 0.62, WAVE = 0.9, STEP = 26; const field = document.getElementById('field'); const cv = document.getElementById('dots'), ctx = cv.getContext('2d'); const btn = document.getElementById('btn'); let W = 0, H = 0, dots = []; let mx = -9999, my = -9999; // cursor in field coordinates let clickAt = null, clickT = 0; function layout() { const r = field.getBoundingClientRect(); W = r.width; H = r.height; cv.width = W * devicePixelRatio; cv.height = H * devicePixelRatio; ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0); dots = []; for (let y = STEP / 2; y < H; y += STEP) for (let x = STEP / 2; x < W; x += STEP) dots.push({ x, y }); } layout(); addEventListener('resize', layout); field.addEventListener('pointermove', e => { const r = field.getBoundingClientRect(); mx = e.clientX - r.left; my = e.clientY - r.top; }); field.addEventListener('pointerleave', () => { mx = my = -9999; }); btn.addEventListener('click', () => { const r = field.getBoundingClientRect(), b = btn.getBoundingClientRect(); clickAt = [b.left - r.left + b.width / 2, b.top - r.top + b.height / 2]; clickT = performance.now(); }); function frame(now) { // the button is pulled by the same formula as the dots, just harder const bx = W / 2, by = H / 2; const bdx = mx - bx, bdy = my - by, br = Math.hypot(bdx, bdy); const bk = Math.max(0, 1 - br / (RADIUS * 1.9)) * BTN_PULL; btn.style.transform = `translate(calc(-50% + ${(bdx * bk).toFixed(1)}px), calc(-50% + ${(bdy * bk).toFixed(1)}px))`; // click wave, a ring spreads out and fades const since = clickAt ? (now - clickT) / 1000 : -1; const wave = since >= 0 && since < 2.4 ? Math.exp(-since * WAVE) : 0; const waveR = since >= 0 ? since * 190 : -1; ctx.clearRect(0, 0, W, H); for (const d of dots) { const dx = mx - d.x, dy = my - d.y; const r = Math.hypot(dx, dy); const k = Math.max(0, 1 - r / RADIUS); let ox = dx * k * PULL, oy = dy * k * PULL; if (wave > 0 && clickAt) { const rb = Math.hypot(d.x - clickAt[0], d.y - clickAt[1]); const gap = Math.abs(rb - waveR); if (gap < 84) { const push = Math.cos(gap / 84 * Math.PI / 2) * wave * 26; const len = Math.max(rb, .001); ox += (d.x - clickAt[0]) / len * push; oy += (d.y - clickAt[1]) / len * push; } } const near = Math.min(1, k * 1.6); const rad = 1.6 + near * 2.6; const px = Math.min(Math.max(d.x + ox, rad), W - rad); const py = Math.min(Math.max(d.y + oy, rad), H - rad); ctx.beginPath(); ctx.arc(px, py, rad, 0, 6.2832); ctx.fillStyle = `rgba(${104 + near * 96 | 0},${116 + near * 108 | 0},${138 + near * 117 | 0},${(.40 + near * .58).toFixed(3)})`; ctx.fill(); } requestAnimationFrame(frame); } requestAnimationFrame(frame);
Tilda, Webflow, WordPress
Нажмите «Скопировать весь код» вверху и вставьте его в один HTML-блок.
Добавить блок, Другое, T123 HTML-код. Вставьте и сохраните. Проверяйте на опубликованной странице, в редакторе скрипты не запускаются.
Панель Add, Embed. Вставьте и нажмите Save & Close. Свой код работает на опубликованном сайте.
Добавить блок, Произвольный HTML. Вставьте и нажмите «Обновить».



