Сердце из тумана
Медленное облако из 600 светящихся точек похоже на шум. Оно поворачивается, мелькает сердце, а потом с одного точного угла каждая точка закрывает свою точку кривой сердца, и сердце светится с вашими словами внутри.
- Частицы и игры
- Бесплатно
- canvas
- particles
- 3d
- Добавлен 24 сентября 2026
<style>
/* Heart Bloom by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
body > .heart-bloom { width: 100vw; height: 100vh; }
/* copy from here */
.heart-bloom {
position: relative; overflow: hidden; cursor: grab; touch-action: none; user-select: none;
-webkit-user-select: none; -webkit-tap-highlight-color: transparent; background: #0a0408;
}
.heart-bloom:active { cursor: grabbing; }
.heart-bloom canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
.heart-bloom .message {
position: absolute; left: 0; right: 0; margin: 0; text-align: center; pointer-events: none;
font: italic 400 34px/1 Georgia, 'Times New Roman', serif; color: #ffe3ec;
text-shadow: 0 0 18px rgba(255, 61, 110, .6);
}
.heart-bloom .message span { display: inline-block; opacity: 0; white-space: pre; }
/* copy to here */
</style>
<!-- copy from here -->
<div class="heart-bloom" role="img" aria-label="A cloud of glowing dots that forms a heart from one angle">
<canvas></canvas>
<p class="message"></p>
</div>
<!-- copy to here -->
<script>
// Heart Bloom by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file
const COUNT = 600, BPM = 72;
const MESSAGE = 'I love you';
const EYE = 60;
const COLORS = ['#ff3d6e', '#ff7cb8'];
const FADE = .22;
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
const easeOutQuint = k => 1 - Math.pow(1 - clamp(k), 5);
const easeInOutCubic = k => (k = clamp(k), k < .5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2);
const rand = (i, k) => { const s = Math.sin(i * 127.1 + k * 311.7) * 43758.5453; return s - Math.floor(s); };
const rad = deg => deg * Math.PI / 180;
const near = deg => ((deg % 360) + 540) % 360 - 180;
const heart = t => [
16 * Math.sin(t) ** 3,
13 * Math.cos(t) - 5 * Math.cos(2 * t)
- 2 * Math.cos(3 * t) - Math.cos(4 * t),
];
// the turn of the cloud in degrees: a slow drift, a glimpse at 1.6 s, a pause, then home at 4.6 s
const TURN = [[0, -100, 40], [1.25, -32, 60], [1.62, 0, 75], [2.05, 24, 35], [2.7, 32, 0]];
const FOCUS = 4.6, LEAVE = 6.9, LOOP = 9;
function hermite(a, b, t) {
const h = b[0] - a[0], u = (t - a[0]) / h, u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * a[1] + (u3 - 2 * u2 + u) * a[2] * h + (3 * u2 - 2 * u3) * b[1] + (u3 - u2) * b[2] * h;
}
function angleAt(t, loop) {
if (t < 2.7) { let i = 0; while (t > TURN[i + 1][0]) i++; return hermite(TURN[i], TURN[i + 1], t); }
if (t < FOCUS) { const u = (t - 2.7) / (FOCUS - 2.7); return 32 * (1 - u) ** 3 * (1 + 3 * u); } // leaves the pause gently, slows right down into focus
if (!loop || t < LEAVE) return 0;
return hermite([LEAVE, 0, 0], [LOOP, 260, 40], Math.min(t, LOOP));
}
// a soft swell of light on every beat, no shaking
function pulse(t) {
if (t < FOCUS + .3) return 0;
const ph = (t - FOCUS - .3) % (60 / BPM);
return Math.exp(-(((ph - .2) / .16) ** 2));
}
// most dots trace the outline, the rest fill the inside more thinly
function makeDots(count) {
const edge = Math.round(count * .7), dots = [];
for (let i = 0; i < count; i++) {
const onEdge = i < edge;
const t = onEdge ? i / edge * Math.PI * 2 : rand(i, 2) * Math.PI * 2;
const r = onEdge ? 1 + (rand(i, 3) - .5) * .035 : .3 + .62 * Math.sqrt(rand(i, 4));
const [hx, hy] = heart(t);
// each dot sits on its own line of sight
const depth = .45 + rand(i, 5) * 1.35;
dots.push({
hx: hx * r, hy: (hy + 2.5) * r, depth, edge: onEdge,
size: onEdge ? 1.1 + rand(i, 7) * .9 : .8 + rand(i, 8) * .6,
glow: onEdge ? .7 + rand(i, 9) * .3 : .3 + rand(i, 10) * .25,
twinkle: [2 + i % 4, rand(i, 15) * 6.28],
tint: Math.floor(rand(i, 11) * 6), hot: rand(i, 12) < .06,
sx: null, sy: 0,
});
}
return dots;
}
// the cloud also tips forward and back, level when the turn is zero and the same after a full turn
const tilt = a => rad(28) * Math.sin(a) + rad(10) * Math.sin(3 * a);
// turn the world by angle a, then look at it from the eye
function look(d, a, words, swell) {
let hy = d.hy;
if (!d.edge && words > 0 && Math.abs(d.hx) < 8) { // the dots inside step aside for the words
const gap = hy - .5;
if (Math.abs(gap) < 3) hy += Math.sign(gap || 1) * (3 - Math.abs(gap)) * .8 * words;
}
const x = d.hx * d.depth * swell;
const y = hy * d.depth * swell;
const z = EYE * (1 - d.depth);
const X = x * Math.cos(a) + z * Math.sin(a);
const Z = z * Math.cos(a) - x * Math.sin(a);
const b = tilt(a);
const Y = y * Math.cos(b) - Z * Math.sin(b);
const k = Math.min(3, EYE / (EYE - Z * Math.cos(b) - y * Math.sin(b)));
return [X * k, Y * k, k];
}
function makeSprites() {
const hex = c => [1, 3, 5].map(i => parseInt(c.slice(i, i + 2), 16));
const [a, b] = COLORS.map(hex), out = [];
for (let i = 0; i <= 6; i++) {
const c = i < 6 ? a.map((v, j) => Math.round(v + (b[j] - v) * i / 5)) : [255, 236, 243];
const s = document.createElement('canvas'); s.width = s.height = 64;
const g = s.getContext('2d'), grad = g.createRadialGradient(32, 32, 0, 32, 32, 32);
grad.addColorStop(0, 'rgba(255,246,250,1)');
grad.addColorStop(.16, `rgba(${c},1)`);
grad.addColorStop(.42, `rgba(${c},.22)`);
grad.addColorStop(1, `rgba(${c},0)`);
g.fillStyle = grad; g.fillRect(0, 0, 64, 64);
out.push(s);
}
return out;
}
// one frame: paint the dark over the last one a little, then add light on top of what is left
function drawHeart(ctx, dots, sprites, t, deg, lay, words, calm) {
const { w, h, cx, cy, s, dpr } = lay;
const a = rad(deg), focus = Math.exp(-((near(deg) / 2.5) ** 2)), beat = calm ? 0 : pulse(t);
const swell = 1 + .015 * beat;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = `rgba(10,4,8,${FADE})`;
ctx.fillRect(0, 0, w, h);
ctx.globalCompositeOperation = 'lighter';
if (!calm && beat > .02 && Math.abs(near(deg)) < 1) { // one soft ring of light on every beat
const ph = (t - FOCUS - .3) % (60 / BPM), k = clamp(ph / .9), grow = 1 + .16 * easeOutQuint(k);
ctx.globalAlpha = .28 * (1 - k) * (1 - k);
ctx.strokeStyle = COLORS[1]; ctx.lineWidth = 1.4;
ctx.beginPath();
for (let i = 0; i <= 120; i++) {
const [x, y] = heart(i / 120 * Math.PI * 2);
const sx = cx + x * grow * s, sy = cy - (y + 2.5) * grow * s;
i ? ctx.lineTo(sx, sy) : ctx.moveTo(sx, sy);
}
ctx.stroke();
}
for (const d of dots) {
const [x, y, k] = look(d, a, words, swell);
const sx = cx + x * s, sy = cy - y * s;
const r = d.size * Math.pow(k, .8) * s * .45;
// a dot that stays put would pile up light every frame, so it only adds what the fade takes away
const moved = d.sx === null ? 1 : clamp(Math.hypot(sx - d.sx, sy - d.sy) / r);
const shine = 1 + .12 * Math.sin(t * d.twinkle[0] * Math.PI * 2 / LOOP + d.twinkle[1]);
d.sx = sx; d.sy = sy;
ctx.globalAlpha = clamp(d.glow * shine * Math.pow(k, .6) * (.55 + .45 * focus + .5 * beat) * (FADE + (1 - FADE) * moved));
const tone = clamp(d.tint + Math.round((k - 1) * 3), 0, 5);
ctx.drawImage(sprites[d.hot ? 6 : tone], sx - r, sy - r, 2 * r, 2 * r);
}
ctx.globalAlpha = 1;
}
// what you see: the room light, the trails, and a small blurred copy of them for the glow
function present(out, trail, glow, t, lay, deg, calm) {
const W = out.canvas.width, H = out.canvas.height, k = lay.dpr;
const gx = lay.cx * k, gy = lay.cy * k, focus = Math.exp(-((near(deg) / 2.5) ** 2));
out.setTransform(1, 0, 0, 1, 0, 0);
out.globalCompositeOperation = 'source-over';
out.drawImage(trail.canvas, 0, 0);
out.globalCompositeOperation = 'lighter';
const room = out.createRadialGradient(gx, gy, 0, gx, gy, lay.s * 22 * k);
room.addColorStop(0, `rgba(255,61,110,${(.05 + .07 * focus + .16 * (calm ? 0 : pulse(t))).toFixed(3)})`);
room.addColorStop(1, 'rgba(255,61,110,0)');
out.fillStyle = room; out.fillRect(0, 0, W, H);
glow.setTransform(1, 0, 0, 1, 0, 0);
glow.clearRect(0, 0, glow.canvas.width, glow.canvas.height);
glow.filter = 'blur(3px)';
glow.drawImage(trail.canvas, 0, 0, glow.canvas.width, glow.canvas.height);
glow.filter = 'none';
out.globalAlpha = .6;
out.drawImage(glow.canvas, 0, 0, W, H);
out.globalAlpha = 1;
out.globalCompositeOperation = 'source-over';
}
// the words come in letter by letter, each one out of a blur
function showWords(note, words, calm) {
if (!note.children.length) for (const ch of MESSAGE) note.append(Object.assign(document.createElement('span'), { textContent: ch }));
[...note.children].forEach((el, i) => {
const k = calm ? 1 : clamp(words * 1.6 - i * .06);
el.style.opacity = k.toFixed(3);
el.style.filter = calm ? 'none' : `blur(${(5 * (1 - k)).toFixed(2)}px)`;
el.style.transform = `translateY(${(5 * (1 - k)).toFixed(2)}px)`;
});
}
const box = document.querySelector('.heart-bloom');
const canvas = box.querySelector('canvas'), view = canvas.getContext('2d');
const ctx = document.createElement('canvas').getContext('2d');
const glow = document.createElement('canvas').getContext('2d');
const note = box.querySelector('.message');
const still = matchMedia('(prefers-reduced-motion: reduce)');
const dots = makeDots(COUNT), sprites = makeSprites();
let lay, t0 = performance.now(), hand = null, words = 0;
function resize() {
const w = box.clientWidth, h = box.clientHeight, dpr = Math.min(devicePixelRatio || 1, 2);
const s = Math.min(w, h) / 40;
lay = { w, h, dpr, s, cx: w / 2, cy: h / 2 };
canvas.width = ctx.canvas.width = Math.round(w * dpr);
canvas.height = ctx.canvas.height = Math.round(h * dpr);
glow.canvas.width = Math.round(w * dpr / 4); glow.canvas.height = Math.round(h * dpr / 4);
ctx.fillStyle = '#0a0408'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
note.style.fontSize = `${Math.round(s * 3)}px`;
note.style.top = `${lay.cy - s * 1.3}px`;
}
// after a drag the cloud turns back home on a spring with no bounce, starting at the speed of your hand
function homeAt(h, now) {
const t = (now - h.t0) / 1000, w = 2 * Math.PI / .8, e0 = h.from - h.to;
return h.to + (e0 + (h.v + w * e0) * t) * Math.exp(-w * t);
}
function frame(now) {
const t = (now - t0) / 1000, calm = still.matches;
let deg = calm ? 0 : angleAt(t, false);
if (hand) deg = hand.down ? hand.a : homeAt(hand, now);
const home = Math.abs(near(deg)) < 3;
const target = home && (calm || t > FOCUS || hand) ? 1 : 0;
words += (target - words) * (calm ? 1 : .06);
drawHeart(ctx, dots, sprites, t, deg, lay, words, calm);
present(view, ctx, glow, t, lay, deg, calm);
showWords(note, words, calm);
requestAnimationFrame(frame);
}
box.addEventListener('pointerdown', e => {
if (still.matches) return;
box.setPointerCapture(e.pointerId);
const now = performance.now(), t = (now - t0) / 1000;
const a = hand ? (hand.down ? hand.a : homeAt(hand, now)) : angleAt(t, false);
hand = { down: true, a, x: e.clientX, v: 0, last: now };
});
box.addEventListener('pointermove', e => {
if (!hand || !hand.down) return;
const now = performance.now(), da = (e.clientX - hand.x) * .35;
hand.v = now > hand.last ? da / (now - hand.last) * 1000 : hand.v;
hand.a += da; hand.x = e.clientX; hand.last = now;
});
const letGo = () => {
if (!hand || !hand.down) return;
const now = performance.now();
hand = { down: false, from: hand.a, to: Math.round(hand.a / 360) * 360, v: now - hand.last > 60 ? 0 : hand.v, t0: now };
};
box.addEventListener('pointerup', letGo);
box.addEventListener('pointercancel', letGo);
addEventListener('resize', resize);
resize();
requestAnimationFrame(frame);
</script>
Оно играет само. Потом потяните облако в сторону, чтобы разбить сердце, и отпустите, оно повернётся обратно и снова найдёт сердце.
Что можно поменять
Поменяйте число, сохраните файл и обновите страницу, разница будет видна сразу.
MESSAGE'I love you'Слова внутри сердца.
EYE60Как далеко глаз стоит от облака. Меньше делает облако глубже и безумнее, больше площе.
BPM72Пульс свечения, когда сердце найдено. 72 это сердце в покое.
COUNT600Сколько точек. Семь из десяти рисуют контур, остальные заполняют.
COLORS['#ff3d6e', '#ff7cb8']Два конца палитры точек, ближние берут светлый конец.
FADE.22Как быстро тают следы. Меньше оставляет более длинные полосы света, пока облако поворачивается.
Как поставить на свой сайт
Любовное письмо или страница предложения, свадебный сайт, промо на день влюблённых, скрытое послание в цифровой открытке, которое человеку нужно повернуть, чтобы найти.
Комментарии в коде на английском, так файл понятен любому разработчику.
CSS
Вставьте в свой файл стилей или в тег <style> внутри <head>.
/* Heart Bloom by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */ body > .heart-bloom { width: 100vw; height: 100vh; } /* copy from here */ .heart-bloom { position: relative; overflow: hidden; cursor: grab; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-tap-highlight-color: transparent; background: #0a0408; } .heart-bloom:active { cursor: grabbing; } .heart-bloom canvas { position: absolute; inset: 0; width: 100%; height: 100%; } .heart-bloom .message { position: absolute; left: 0; right: 0; margin: 0; text-align: center; pointer-events: none; font: italic 400 34px/1 Georgia, 'Times New Roman', serif; color: #ffe3ec; text-shadow: 0 0 18px rgba(255, 61, 110, .6); } .heart-bloom .message span { display: inline-block; opacity: 0; white-space: pre; } /* copy to here */HTML
Поставьте в то место страницы, где должен быть эффект.
<!-- copy from here --> <div class="heart-bloom" role="img" aria-label="A cloud of glowing dots that forms a heart from one angle"> <canvas></canvas> <p class="message"></p> </div> <!-- copy to here -->JavaScript
Вставьте перед закрывающим тегом </body>, внутри <script></script>.
// Heart Bloom by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file const COUNT = 600, BPM = 72; const MESSAGE = 'I love you'; const EYE = 60; const COLORS = ['#ff3d6e', '#ff7cb8']; const FADE = .22; const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x)); const easeOutQuint = k => 1 - Math.pow(1 - clamp(k), 5); const easeInOutCubic = k => (k = clamp(k), k < .5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2); const rand = (i, k) => { const s = Math.sin(i * 127.1 + k * 311.7) * 43758.5453; return s - Math.floor(s); }; const rad = deg => deg * Math.PI / 180; const near = deg => ((deg % 360) + 540) % 360 - 180; const heart = t => [ 16 * Math.sin(t) ** 3, 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t), ]; // the turn of the cloud in degrees: a slow drift, a glimpse at 1.6 s, a pause, then home at 4.6 s const TURN = [[0, -100, 40], [1.25, -32, 60], [1.62, 0, 75], [2.05, 24, 35], [2.7, 32, 0]]; const FOCUS = 4.6, LEAVE = 6.9, LOOP = 9; function hermite(a, b, t) { const h = b[0] - a[0], u = (t - a[0]) / h, u2 = u * u, u3 = u2 * u; return (2 * u3 - 3 * u2 + 1) * a[1] + (u3 - 2 * u2 + u) * a[2] * h + (3 * u2 - 2 * u3) * b[1] + (u3 - u2) * b[2] * h; } function angleAt(t, loop) { if (t < 2.7) { let i = 0; while (t > TURN[i + 1][0]) i++; return hermite(TURN[i], TURN[i + 1], t); } if (t < FOCUS) { const u = (t - 2.7) / (FOCUS - 2.7); return 32 * (1 - u) ** 3 * (1 + 3 * u); } // leaves the pause gently, slows right down into focus if (!loop || t < LEAVE) return 0; return hermite([LEAVE, 0, 0], [LOOP, 260, 40], Math.min(t, LOOP)); } // a soft swell of light on every beat, no shaking function pulse(t) { if (t < FOCUS + .3) return 0; const ph = (t - FOCUS - .3) % (60 / BPM); return Math.exp(-(((ph - .2) / .16) ** 2)); } // most dots trace the outline, the rest fill the inside more thinly function makeDots(count) { const edge = Math.round(count * .7), dots = []; for (let i = 0; i < count; i++) { const onEdge = i < edge; const t = onEdge ? i / edge * Math.PI * 2 : rand(i, 2) * Math.PI * 2; const r = onEdge ? 1 + (rand(i, 3) - .5) * .035 : .3 + .62 * Math.sqrt(rand(i, 4)); const [hx, hy] = heart(t); // each dot sits on its own line of sight const depth = .45 + rand(i, 5) * 1.35; dots.push({ hx: hx * r, hy: (hy + 2.5) * r, depth, edge: onEdge, size: onEdge ? 1.1 + rand(i, 7) * .9 : .8 + rand(i, 8) * .6, glow: onEdge ? .7 + rand(i, 9) * .3 : .3 + rand(i, 10) * .25, twinkle: [2 + i % 4, rand(i, 15) * 6.28], tint: Math.floor(rand(i, 11) * 6), hot: rand(i, 12) < .06, sx: null, sy: 0, }); } return dots; } // the cloud also tips forward and back, level when the turn is zero and the same after a full turn const tilt = a => rad(28) * Math.sin(a) + rad(10) * Math.sin(3 * a); // turn the world by angle a, then look at it from the eye function look(d, a, words, swell) { let hy = d.hy; if (!d.edge && words > 0 && Math.abs(d.hx) < 8) { // the dots inside step aside for the words const gap = hy - .5; if (Math.abs(gap) < 3) hy += Math.sign(gap || 1) * (3 - Math.abs(gap)) * .8 * words; } const x = d.hx * d.depth * swell; const y = hy * d.depth * swell; const z = EYE * (1 - d.depth); const X = x * Math.cos(a) + z * Math.sin(a); const Z = z * Math.cos(a) - x * Math.sin(a); const b = tilt(a); const Y = y * Math.cos(b) - Z * Math.sin(b); const k = Math.min(3, EYE / (EYE - Z * Math.cos(b) - y * Math.sin(b))); return [X * k, Y * k, k]; } function makeSprites() { const hex = c => [1, 3, 5].map(i => parseInt(c.slice(i, i + 2), 16)); const [a, b] = COLORS.map(hex), out = []; for (let i = 0; i <= 6; i++) { const c = i < 6 ? a.map((v, j) => Math.round(v + (b[j] - v) * i / 5)) : [255, 236, 243]; const s = document.createElement('canvas'); s.width = s.height = 64; const g = s.getContext('2d'), grad = g.createRadialGradient(32, 32, 0, 32, 32, 32); grad.addColorStop(0, 'rgba(255,246,250,1)'); grad.addColorStop(.16, `rgba(${c},1)`); grad.addColorStop(.42, `rgba(${c},.22)`); grad.addColorStop(1, `rgba(${c},0)`); g.fillStyle = grad; g.fillRect(0, 0, 64, 64); out.push(s); } return out; } // one frame: paint the dark over the last one a little, then add light on top of what is left function drawHeart(ctx, dots, sprites, t, deg, lay, words, calm) { const { w, h, cx, cy, s, dpr } = lay; const a = rad(deg), focus = Math.exp(-((near(deg) / 2.5) ** 2)), beat = calm ? 0 : pulse(t); const swell = 1 + .015 * beat; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.globalCompositeOperation = 'source-over'; ctx.fillStyle = `rgba(10,4,8,${FADE})`; ctx.fillRect(0, 0, w, h); ctx.globalCompositeOperation = 'lighter'; if (!calm && beat > .02 && Math.abs(near(deg)) < 1) { // one soft ring of light on every beat const ph = (t - FOCUS - .3) % (60 / BPM), k = clamp(ph / .9), grow = 1 + .16 * easeOutQuint(k); ctx.globalAlpha = .28 * (1 - k) * (1 - k); ctx.strokeStyle = COLORS[1]; ctx.lineWidth = 1.4; ctx.beginPath(); for (let i = 0; i <= 120; i++) { const [x, y] = heart(i / 120 * Math.PI * 2); const sx = cx + x * grow * s, sy = cy - (y + 2.5) * grow * s; i ? ctx.lineTo(sx, sy) : ctx.moveTo(sx, sy); } ctx.stroke(); } for (const d of dots) { const [x, y, k] = look(d, a, words, swell); const sx = cx + x * s, sy = cy - y * s; const r = d.size * Math.pow(k, .8) * s * .45; // a dot that stays put would pile up light every frame, so it only adds what the fade takes away const moved = d.sx === null ? 1 : clamp(Math.hypot(sx - d.sx, sy - d.sy) / r); const shine = 1 + .12 * Math.sin(t * d.twinkle[0] * Math.PI * 2 / LOOP + d.twinkle[1]); d.sx = sx; d.sy = sy; ctx.globalAlpha = clamp(d.glow * shine * Math.pow(k, .6) * (.55 + .45 * focus + .5 * beat) * (FADE + (1 - FADE) * moved)); const tone = clamp(d.tint + Math.round((k - 1) * 3), 0, 5); ctx.drawImage(sprites[d.hot ? 6 : tone], sx - r, sy - r, 2 * r, 2 * r); } ctx.globalAlpha = 1; } // what you see: the room light, the trails, and a small blurred copy of them for the glow function present(out, trail, glow, t, lay, deg, calm) { const W = out.canvas.width, H = out.canvas.height, k = lay.dpr; const gx = lay.cx * k, gy = lay.cy * k, focus = Math.exp(-((near(deg) / 2.5) ** 2)); out.setTransform(1, 0, 0, 1, 0, 0); out.globalCompositeOperation = 'source-over'; out.drawImage(trail.canvas, 0, 0); out.globalCompositeOperation = 'lighter'; const room = out.createRadialGradient(gx, gy, 0, gx, gy, lay.s * 22 * k); room.addColorStop(0, `rgba(255,61,110,${(.05 + .07 * focus + .16 * (calm ? 0 : pulse(t))).toFixed(3)})`); room.addColorStop(1, 'rgba(255,61,110,0)'); out.fillStyle = room; out.fillRect(0, 0, W, H); glow.setTransform(1, 0, 0, 1, 0, 0); glow.clearRect(0, 0, glow.canvas.width, glow.canvas.height); glow.filter = 'blur(3px)'; glow.drawImage(trail.canvas, 0, 0, glow.canvas.width, glow.canvas.height); glow.filter = 'none'; out.globalAlpha = .6; out.drawImage(glow.canvas, 0, 0, W, H); out.globalAlpha = 1; out.globalCompositeOperation = 'source-over'; } // the words come in letter by letter, each one out of a blur function showWords(note, words, calm) { if (!note.children.length) for (const ch of MESSAGE) note.append(Object.assign(document.createElement('span'), { textContent: ch })); [...note.children].forEach((el, i) => { const k = calm ? 1 : clamp(words * 1.6 - i * .06); el.style.opacity = k.toFixed(3); el.style.filter = calm ? 'none' : `blur(${(5 * (1 - k)).toFixed(2)}px)`; el.style.transform = `translateY(${(5 * (1 - k)).toFixed(2)}px)`; }); } const box = document.querySelector('.heart-bloom'); const canvas = box.querySelector('canvas'), view = canvas.getContext('2d'); const ctx = document.createElement('canvas').getContext('2d'); const glow = document.createElement('canvas').getContext('2d'); const note = box.querySelector('.message'); const still = matchMedia('(prefers-reduced-motion: reduce)'); const dots = makeDots(COUNT), sprites = makeSprites(); let lay, t0 = performance.now(), hand = null, words = 0; function resize() { const w = box.clientWidth, h = box.clientHeight, dpr = Math.min(devicePixelRatio || 1, 2); const s = Math.min(w, h) / 40; lay = { w, h, dpr, s, cx: w / 2, cy: h / 2 }; canvas.width = ctx.canvas.width = Math.round(w * dpr); canvas.height = ctx.canvas.height = Math.round(h * dpr); glow.canvas.width = Math.round(w * dpr / 4); glow.canvas.height = Math.round(h * dpr / 4); ctx.fillStyle = '#0a0408'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); note.style.fontSize = `${Math.round(s * 3)}px`; note.style.top = `${lay.cy - s * 1.3}px`; } // after a drag the cloud turns back home on a spring with no bounce, starting at the speed of your hand function homeAt(h, now) { const t = (now - h.t0) / 1000, w = 2 * Math.PI / .8, e0 = h.from - h.to; return h.to + (e0 + (h.v + w * e0) * t) * Math.exp(-w * t); } function frame(now) { const t = (now - t0) / 1000, calm = still.matches; let deg = calm ? 0 : angleAt(t, false); if (hand) deg = hand.down ? hand.a : homeAt(hand, now); const home = Math.abs(near(deg)) < 3; const target = home && (calm || t > FOCUS || hand) ? 1 : 0; words += (target - words) * (calm ? 1 : .06); drawHeart(ctx, dots, sprites, t, deg, lay, words, calm); present(view, ctx, glow, t, lay, deg, calm); showWords(note, words, calm); requestAnimationFrame(frame); } box.addEventListener('pointerdown', e => { if (still.matches) return; box.setPointerCapture(e.pointerId); const now = performance.now(), t = (now - t0) / 1000; const a = hand ? (hand.down ? hand.a : homeAt(hand, now)) : angleAt(t, false); hand = { down: true, a, x: e.clientX, v: 0, last: now }; }); box.addEventListener('pointermove', e => { if (!hand || !hand.down) return; const now = performance.now(), da = (e.clientX - hand.x) * .35; hand.v = now > hand.last ? da / (now - hand.last) * 1000 : hand.v; hand.a += da; hand.x = e.clientX; hand.last = now; }); const letGo = () => { if (!hand || !hand.down) return; const now = performance.now(); hand = { down: false, from: hand.a, to: Math.round(hand.a / 360) * 360, v: now - hand.last > 60 ? 0 : hand.v, t0: now }; }; box.addEventListener('pointerup', letGo); box.addEventListener('pointercancel', letGo); addEventListener('resize', resize); resize(); requestAnimationFrame(frame);
Подключение к серверу
Здесь ничего не обращается к серверу. Чтобы показывать каждому посетителю своё послание, подставляйте текст с сервера в MESSAGE до запуска скрипта.
Полезно знать
- Каждая точка стоит где-то на своей линии взгляда через точку кривой сердца x = 16 sin³t, y = 13 cos t - 5 cos 2t - 2 cos 3t - cos 4t, на случайной глубине, поэтому из глаза она закрывает свою точку, а с любого другого места облако это шум.
- Картинка это обычная перспектива. Поворачиваем мир на угол и делим на расстояние до глаза.
- Облако ещё и наклоняется вперёд и назад по кривой, которая ровная при нулевом повороте и повторяется через полный оборот.
- Подход к фокусу сильно замедляется, поэтому сердце выходит из полос света, а не выскакивает.
- Следы получаются закраской тёмного фона поверх прошлого кадра, а стоящая точка добавляет только тот свет, который забрала краска, поэтому контур остаётся из искр.
- Свечение это размытая копия света в четверть размера поверх картинки, и комната мягко светлеет на каждом ударе. Само сердце почти не движется, ничего не трясётся.
- Если разбить облако, оно возвращается домой на пружине без отскока, начиная со скорости руки.
- При уменьшении движения сразу показывает сердце и слова и не реагирует на перетаскивание.
Tilda, Webflow, WordPress
Нажмите «Скопировать весь код» вверху и вставьте его в один HTML-блок.
Добавить блок, Другое, T123 HTML-код. Вставьте и сохраните. Проверяйте на опубликованной странице, в редакторе скрипты не запускаются.
Панель Add, Embed. Вставьте и нажмите Save & Close. Свой код работает на опубликованном сайте.
Добавить блок, Произвольный HTML. Вставьте и нажмите «Обновить».



