Кодовый замок

Латунный замок с тремя колёсиками. Крутите их пальцем, как настоящие. Наберите верный код, и замок откроется, а изнутри выедет купон со скидкой.

Прокрутите колёсико вверх или вниз или нажмите на него, чтобы сдвинуть на одну цифру. Код 4 8 1. Нажмите на открытый замок, чтобы закрыть его.

Скачать

Что можно поменять

Поменяйте число, сохраните файл и обновите страницу, разница будет видна сразу.

COMBO[4, 8, 1]

Код, который открывает замок. Спрячьте его в сторис, письмах или на упаковке.

REWARD'SECRET30'

Купон, который выезжает, когда замок открывается.

FRICTION0.997

Как далеко уносит бросок. 0.997 катится долго, 0.99 быстро останавливается.

DAMPING0.7

Ниже 1 сильный бросок прокатывается мимо цифры и обратно. 1 встаёт точно.

FACE44

Высота одной цифры на барабане, держите равной .face в CSS.

Как поставить на свой сайт

Секретная скидка для подписчиков, промокод, который нужно найти, подарок или ранний доступ к запуску.

Комментарии в коде на английском, так файл понятен любому разработчику.

  1. CSS

    Вставьте в свой файл стилей или в тег <style> внутри <head>.

    /* Secret Sale Lock by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
    /* copy from here */
    .gate { width: min(380px, calc(100vw - 24px)); padding: 24px 22px 20px; border-radius: 28px; text-align: center; box-sizing: border-box;
    background: linear-gradient(180deg, #17161480, #0F0F0E); box-shadow: inset 0 1px 0 rgba(255,240,210,.08), 0 0 0 1px rgba(255,240,210,.06), 0 40px 80px -40px #000; }
    .gate h1 { margin: 0; font-size: 22px; line-height: 1.2; letter-spacing: -.02em; font-weight: 750; }
    .gate p { margin: 6px 0 0; color: #948C7D; font-size: 14px; }
    
    /* the scene: one perspective, the whole lock is a real 3D block that leans a little while you flick */
    .stage { position: relative; height: 290px; perspective: 1000px; perspective-origin: 50% 35%; touch-action: none; }
    .lock { position: absolute; left: 50%; top: 71%; width: 0; height: 0; transform-style: preserve-3d; }
    .lock > * { position: absolute; left: 0; top: 0; transform-style: preserve-3d; backface-visibility: hidden; }
    .side { box-shadow: inset 0 0 0 1px rgba(255,236,190,.08); }
    .front { width: 280px; height: 190px;
    background: linear-gradient(180deg, rgba(255,246,214,.30), rgba(255,246,214,0) 22%, rgba(0,0,0,0) 70%, rgba(40,24,0,.40)),
      repeating-linear-gradient(90deg, rgba(255,255,255,.04) 0 1px, rgba(0,0,0,.035) 1px 3px),
      linear-gradient(90deg, #7A5A1E, #C2944A 22%, #EBCB84 42%, #D6AC5A 62%, #9C7430 100%); }
    .top { width: 280px; height: 100px;
    background: radial-gradient(circle 17px at 54px 50px, #090705 50%, #2C200C 80%, rgba(60,44,16,0) 100%),
      radial-gradient(circle 17px at 226px 50px, #090705 50%, #2C200C 80%, rgba(60,44,16,0) 100%),
      radial-gradient(ellipse 36px 24px at 64px 58px, rgba(52,32,6,.5), rgba(52,32,6,0) 72%),
      radial-gradient(ellipse 36px 24px at 236px 58px, rgba(52,32,6,.5), rgba(52,32,6,0) 72%),
      radial-gradient(ellipse 130px 46px at 32% 34%, rgba(255,251,230,.55), rgba(255,251,230,0) 70%),
      repeating-linear-gradient(90deg, rgba(255,255,255,.07) 0 1px, rgba(60,40,0,.06) 1px 2px, rgba(0,0,0,0) 2px 4px),
      linear-gradient(180deg, #A97E34, #D9B064 40%, #EFCF86 75%, #FFE9B0); }
    /* rounded edges: narrow faces at 45 degrees catch the light the way a machined edge does */
    .bevel { background: linear-gradient(180deg, #FFF6D6, #F2D38C 45%, #C9A04E); }
    .bevel.side { background: linear-gradient(90deg, #6E5019, #C9A04E 60%, #F2D38C); }
    .left { width: 100px; height: 190px; background: linear-gradient(180deg, #8C6A2C, #5E4214 75%, #3E2B0C); box-shadow: inset -2px 0 0 rgba(255,236,190,.35); }
    .right, .back, .bottom { background: #3A2A0E; }
    .wall.t { background: linear-gradient(180deg, #120D05, #2E2210); }
    .wall.b { background: linear-gradient(0deg, #6E5220, #A67F3A); }
    .wall.l { background: linear-gradient(90deg, #2A1F0C, #47351A); }
    .wall.r { background: linear-gradient(270deg, #5C4418, #8A6829); }
    .face { width: 50px; height: 44px; display: grid; place-items: center; padding-top: 4px; box-sizing: border-box; pointer-events: none;
    background: linear-gradient(90deg, #1D2025, #3A3F47 30%, #474C55 50%, #3A3F47 70%, #1D2025);
    font: 700 38px/1 "DIN Condensed", "Bahnschrift", system-ui, sans-serif; color: #F3F1EA; text-shadow: 0 -1px 0 rgba(0,0,0,.7); }
    .face::after { content: ""; position: absolute; inset: 0; background: #000; opacity: var(--shade, 0); }
    .hit { width: 56px; height: 92px; border-radius: 8px; cursor: grab; outline: 0; }
    .hit:focus-visible { box-shadow: 0 0 0 3px #F7E0A0; }
    .shackle { width: 200px; height: 230px; overflow: visible; }
    .shackle path { fill: none; }
    .steel { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
    .floor { width: 320px; height: 160px; background: radial-gradient(ellipse 50% 50% at 50% 50%, rgba(0,0,0,.75), rgba(0,0,0,0) 70%); }
    
    /* the coupon slides out of a slot under the lock once the code is right */
    .reward { position: relative; height: 76px; margin-top: 4px; }
    .reward > * { position: absolute; inset: 0; display: flex; flex-wrap: wrap; align-content: center; align-items: center; justify-content: center; gap: 8px 10px; transition: opacity .25s ease-out, transform .35s cubic-bezier(.23, 1, .32, 1); }
    .hint { color: #948C7D; font-size: 14px; }
    .coupon { opacity: 0; transform: translateY(10px) scale(.97); pointer-events: none; }
    .coupon b { width: 100%; font-size: 17px; letter-spacing: -.01em; }
    .coupon code { padding: 7px 12px; border-radius: 10px; border: 1.5px dashed #C9A45A; color: #F2D58A; font: 700 16px/1 Menlo, monospace; letter-spacing: .06em; }
    .coupon button { height: 34px; padding: 0 14px; border: 0; border-radius: 10px; background: #F2D58A; color: #1A1200; font: 700 14px system-ui, sans-serif; cursor: pointer; }
    .coupon button:active { transform: scale(.97); }
    .gate.open .hint { opacity: 0; transform: translateY(-8px); }
    .gate.open .coupon { opacity: 1; transform: none; pointer-events: auto; }
    @media (prefers-reduced-motion: reduce) { .reward > * { transition: opacity .2s ease; transform: none !important; } }
    /* copy to here */
  2. HTML

    Поставьте в то место страницы, где должен быть эффект.

    <!-- copy from here -->
    <section class="gate" aria-label="Secret sale">
      <h1>The secret sale is locked</h1>
      <p>The code is hidden in our last three stories.</p>
      <div class="stage">
        <div class="lock" role="group" aria-label="Combination lock"></div>
        <canvas class="steel" aria-hidden="true"></canvas>
      </div>
      <div class="reward" aria-live="polite">
        <span class="hint">Flick the wheels to enter it</span>
        <span class="coupon"><b>30% off everything</b><code></code><button type="button">Copy</button></span>
      </div>
    </section>
    <!-- copy to here -->
  3. JavaScript

    Вставьте перед закрывающим тегом </body>, внутри <script></script>.

    // Secret Sale Lock by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file
    const COMBO = [4, 8, 1];
    const REWARD = 'SECRET30';     // the coupon it unlocks
    const FRICTION = 0.997;  // how far a flick carries
    const DAMPING = 0.7;     // under 1 rolls past and back
    const FACE = 44;         // px per digit, same as .face height
    
    const gate = document.querySelector('.gate'), lock = gate.querySelector('.lock');
    const still = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
    const R = FACE / 2 / Math.tan(Math.PI / 10);
    const wrap10 = n => ((n % 10) + 10) % 10;
    gate.querySelector('code').textContent = REWARD;
    let open = false, closing = false, running = false;
    
    // the block: 280 wide, 190 tall, 100 deep, centred on the origin, windows cut through the front
    const W = 280, H = 190, D = 100, WIN = { w: 56, h: 92, y: 40, x: [42, 112, 182], deep: 16 };
    function part(cls, w, h, t) {
    const el = document.createElement('div');
    el.className = cls; el.style.width = w + 'px'; el.style.height = h + 'px';
    el.style.transform = `translate(${-w / 2}px, ${-h / 2}px) ${t}`;
    lock.append(el);
    return el;
    }
    const rounded = (x, y, w, h, r) => `M${x + r} ${y}h${w - 2 * r}a${r} ${r} 0 0 1 ${r} ${r}v${h - 2 * r}a${r} ${r} 0 0 1 ${-r} ${r}h${2 * r - w}a${r} ${r} 0 0 1 ${-r} ${-r}v${2 * r - h}a${r} ${r} 0 0 1 ${r} ${-r}Z`;
    const cut = `M0 0H${W}V${H}H0Z` + WIN.x.map(x => rounded(x, WIN.y, WIN.w, WIN.h, 8)).join('');
    const floor = part('floor', 320, 160, `translate3d(0, ${H / 2 + 2}px, 0) rotateX(90deg)`);
    part('side back', W, H, `rotateY(180deg) translateZ(${D / 2}px)`);
    part('side bottom', W, D, `translateY(${H / 2}px) rotateX(-90deg)`);
    part('side right', D, H, `translateX(${W / 2}px) rotateY(90deg)`);
    part('side left', D, H, `translateX(${-W / 2}px) rotateY(-90deg)`);
    part('side top', W, D, `translateY(${-H / 2}px) rotateX(90deg)`);
    part('bevel', W, 7, `translate3d(0, ${-H / 2 + 1.5}px, ${D / 2 - 1.5}px) rotateX(45deg)`);
    part('bevel side', 7, H, `translate3d(${-W / 2 + 1.5}px, 0, ${D / 2 - 1.5}px) rotateY(-45deg)`);
    part('bevel side', D, 7, `translate3d(${-W / 2 + 1.5}px, ${-H / 2 + 1.5}px, 0) rotateY(-90deg) rotateX(45deg)`);
    
    // every window is a real recess: four walls going in, a drum of ten digits behind them
    const wheels = WIN.x.map((x, i) => {
    const cx = x + WIN.w / 2 - W / 2, cy = WIN.y + WIN.h / 2 - H / 2, z = D / 2;
    part('wall t', WIN.w, WIN.deep, `translate3d(${cx}px, ${cy - WIN.h / 2}px, ${z - WIN.deep / 2}px) rotateX(-90deg)`);
    part('wall b', WIN.w, WIN.deep, `translate3d(${cx}px, ${cy + WIN.h / 2}px, ${z - WIN.deep / 2}px) rotateX(90deg)`);
    part('wall l', WIN.deep, WIN.h, `translate3d(${cx - WIN.w / 2}px, ${cy}px, ${z - WIN.deep / 2}px) rotateY(90deg)`);
    part('wall r', WIN.deep, WIN.h, `translate3d(${cx + WIN.w / 2}px, ${cy}px, ${z - WIN.deep / 2}px) rotateY(-90deg)`);
    const drum = part('drum', 0, 0, `translate3d(${cx}px, ${cy}px, ${z - WIN.deep - R + 4}px)`);
    const faces = [...Array(10)].map((_, n) => {
      const f = document.createElement('b');
      f.className = 'face'; f.textContent = n;
      f.style.position = 'absolute';
      f.style.transform = `translate(-25px, -22px) rotateX(${-n * 36}deg) translateZ(${R.toFixed(2)}px)`;
      drum.append(f);
      return f;
    });
    return { drum, faces, base: drum.style.transform, pos: 0, v: 0, s: null, drag: null, cx, cy, z };
    });
    const front = part('side front', W, H, `translateZ(${D / 2}px)`);
    front.style.webkitMask = front.style.mask = `url("data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='${W}' height='${H}'><path fill-rule='evenodd' d='${cut}'/></svg>`)}")`;
    wheels.forEach((w, i) => {
    w.el = part('hit', WIN.w, WIN.h, `translate3d(${w.cx}px, ${w.cy}px, ${w.z + .5}px)`);
    w.el.tabIndex = 0; w.el.setAttribute('role', 'spinbutton'); w.el.setAttribute('aria-label', `Digit ${i + 1}`);
    w.el.setAttribute('aria-valuemin', 0); w.el.setAttribute('aria-valuemax', 9); w.el.setAttribute('aria-valuenow', 0);
    });
    
    // the shackle: one steel tube, the same path stroked from dark rim to bright core; its legs go through the top into the holes
    const TUBE = 'M14 170V100A86 86 0 0 1 186 100V220';
    lock.insertAdjacentHTML('beforeend', `<svg class="shackle" viewBox="0 0 200 230" aria-hidden="true">
    <defs><mask id="tube" maskUnits="userSpaceOnUse" x="-20" y="-20" width="240" height="270"><path d="${TUBE}" stroke="#fff" stroke-width="28"/></mask>
      <filter id="b1" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="1"/></filter>
      <filter id="b2" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="2.2"/></filter>
      <filter id="b4" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="4.5"/></filter></defs>
    <g mask="url(#tube)">
      <path d="${TUBE}" stroke="#7B848F" stroke-width="40"/>
      <path d="${TUBE}" stroke="#262A31" stroke-width="30" transform="translate(9 7)" filter="url(#b4)"/>
      <path d="${TUBE}" stroke="rgba(226,178,96,.45)" stroke-width="5" transform="translate(13 11)" filter="url(#b2)"/>
      <path d="${TUBE}" stroke="#C5CCD4" stroke-width="15" transform="translate(-4 -4)" filter="url(#b4)"/>
      <path d="${TUBE}" stroke="rgba(28,33,40,.6)" stroke-width="2.5" transform="translate(1 1)" filter="url(#b1)"/>
      <path d="${TUBE}" stroke="#FFFFFF" stroke-width="5" transform="translate(-6 -6)" filter="url(#b2)"/>
      <path d="${TUBE}" stroke="#FFFFFF" stroke-width="1.6" transform="translate(-7 -7)"/>
      <path d="M14 156V162" stroke="rgba(14,16,20,.7)" stroke-width="30"/><path d="M14 162V163.2" stroke="rgba(255,255,255,.4)" stroke-width="30"/>
    </g></svg>`);
    const shackle = lock.querySelector('.shackle');
    shackle.style.transformOrigin = '186px 148px';
    
    // the shackle itself is a real steel tube drawn with WebGL in exactly the perspective of the CSS block,
    // so it keeps its round volume when the lock leans and when it swings open; the SVG above is the fallback
    const steel = (() => {
    const cv = gate.querySelector('.steel'), g = cv.getContext('webgl', { antialias: true, premultipliedAlpha: true, alpha: true });
    if (!g) return null;
    const vs = `attribute vec3 p; attribute vec3 n; attribute float s;
      uniform mat3 R; uniform vec2 turn; uniform float lift, S; uniform vec3 O; uniform vec2 PO, size;
      varying vec3 vN, vP; varying float vS, vY;
      void main() {
        vec3 q = p - vec3(86., 0., 0.);
        q = vec3(q.x * turn.x + q.z * turn.y, q.y, -q.x * turn.y + q.z * turn.x) + vec3(86., -lift, 0.);
        vec3 m = vec3(n.x * turn.x + n.z * turn.y, n.y, -n.x * turn.y + n.z * turn.x);
        vY = q.y; vS = s;
        vec3 w = R * (q * S) + O;
        vN = R * m; vP = w;
        vec2 sp = PO + (w.xy - PO) * 1000. / (1000. - w.z);
        gl_Position = vec4(sp.x / size.x * 2. - 1., 1. - sp.y / size.y * 2., -w.z / 2000., 1.);
      }`;
    const fs = `precision highp float;
      varying vec3 vN, vP; varying float vS, vY; uniform vec2 PO;
      void main() {
        if (vY > -95.) discard;
        vec3 N = normalize(vN), V = normalize(vec3(PO, 1000.) - vP), r = reflect(-V, N);
        float up = -r.y;
        // a photo studio around the lock: bright ceiling, dark horizon line, warm brass floor, a softbox and a strip light
        vec3 env = up > 0. ? mix(vec3(.62, .64, .68), vec3(.97, .98, 1.), smoothstep(0., .8, up))
                           : mix(vec3(.58, .58, .6), vec3(.3, .25, .17), smoothstep(0., -.8, up));
        env *= 1. - .7 * exp(-up * up / .0025);
        env += .4 * smoothstep(.45, 1., r.z);
        env += 1.3 * smoothstep(.9, .975, dot(r, normalize(vec3(-.35, -.55, .75))));
        env += .9 * smoothstep(.985, .998, dot(r, normalize(vec3(.85, -.15, .5))));
        vec3 L = normalize(vec3(-.55, -.75, .55));
        vec3 col = env * vec3(.9, .93, .97) + pow(max(dot(r, L), 0.), 120.) * 1.4;
        col *= .9 + .1 * max(dot(N, -L), 0.);
        float notch = smoothstep(7., 8., vS) * (1. - smoothstep(13., 14., vS));
        col *= 1. - .6 * notch;
        gl_FragColor = vec4(col, 1.);
      }`;
    const sh2 = (type, src) => { const x = g.createShader(type); g.shaderSource(x, src); g.compileShader(x); return x; };
    const pr = g.createProgram(); g.attachShader(pr, sh2(g.VERTEX_SHADER, vs)); g.attachShader(pr, sh2(g.FRAGMENT_SHADER, fs)); g.linkProgram(pr);
    if (!g.getProgramParameter(pr, g.LINK_STATUS)) return null;
    // sweep a round section along the U: toe leg up, half circle over the top, heel leg down
    const path = [];
    for (let i = 0; i <= 6; i++) path.push([-86, -73 - 70 * i / 6]);
    for (let i = 1; i < 48; i++) { const a = Math.PI * i / 48; path.push([-86 * Math.cos(a), -143 - 86 * Math.sin(a)]); }
    for (let i = 0; i <= 10; i++) path.push([86, -143 + 120 * i / 10]);
    const RING = 24, rad = 14, pos = [], nor = [], arc = [], idx = [];
    let len = 0;
    path.forEach((c, i) => {
      const a = path[Math.max(0, i - 1)], b = path[Math.min(path.length - 1, i + 1)];
      let tx = b[0] - a[0], ty = b[1] - a[1]; const tl = Math.hypot(tx, ty); tx /= tl; ty /= tl;
      if (i) len += Math.hypot(c[0] - path[i - 1][0], c[1] - path[i - 1][1]);
      for (let k = 0; k <= RING; k++) {
        const u = 2 * Math.PI * k / RING, nx = -ty * Math.cos(u), ny = tx * Math.cos(u), nz = Math.sin(u);
        pos.push(c[0] + nx * rad, c[1] + ny * rad, nz * rad); nor.push(nx, ny, nz); arc.push(len);
      }
    });
    for (let i = 0; i < path.length - 1; i++) for (let k = 0; k < RING; k++) {
      const a = i * (RING + 1) + k, b = a + RING + 1;
      idx.push(a, b, a + 1, a + 1, b, b + 1);
    }
    // a flat cap on the toe end, seen when the shackle pops out
    const cap = pos.length / 3; pos.push(-86, -73, 0); nor.push(0, 1, 0); arc.push(0);
    for (let k = 0; k <= RING; k++) { pos.push(pos[k * 3], -73, pos[k * 3 + 2]); nor.push(0, 1, 0); arc.push(0); }
    for (let k = 0; k < RING; k++) idx.push(cap, cap + 1 + k, cap + 2 + k);
    const buf = (data, name, size) => {
      const b = g.createBuffer(); g.bindBuffer(g.ARRAY_BUFFER, b); g.bufferData(g.ARRAY_BUFFER, new Float32Array(data), g.STATIC_DRAW);
      const loc = g.getAttribLocation(pr, name); g.enableVertexAttribArray(loc); g.vertexAttribPointer(loc, size, g.FLOAT, false, 0, 0);
    };
    g.useProgram(pr); buf(pos, 'p', 3); buf(nor, 'n', 3); buf(arc, 's', 1);
    const ib = g.createBuffer(); g.bindBuffer(g.ELEMENT_ARRAY_BUFFER, ib); g.bufferData(g.ELEMENT_ARRAY_BUFFER, new Uint16Array(idx), g.STATIC_DRAW);
    const U = name => g.getUniformLocation(pr, name);
    g.enable(g.DEPTH_TEST);
    shackle.style.display = 'none';
    return (rx, ry, lift, turn) => {
      const box = cv.getBoundingClientRect(), W = cv.offsetWidth, H = cv.offsetHeight, dpr = Math.min(3, (window.devicePixelRatio || 1) * 1.5);
      if (cv.width !== Math.round(W * dpr)) { cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr); }
      g.viewport(0, 0, cv.width, cv.height); g.clearColor(0, 0, 0, 0); g.clear(g.COLOR_BUFFER_BIT | g.DEPTH_BUFFER_BIT);
      const a = rx * Math.PI / 180, b = ry * Math.PI / 180, ca = Math.cos(a), sa = Math.sin(a), cb = Math.cos(b), sb = Math.sin(b);
      // CSS rotateX(a) rotateY(b), column-major for WebGL
      g.uniformMatrix3fv(U('R'), false, [cb, sa * sb, -ca * sb, 0, ca, sa, sb, -sa * cb, ca * cb]);
      const tt = turn * Math.PI / 180;
      g.uniform2f(U('turn'), Math.cos(tt), Math.sin(tt)); g.uniform1f(U('lift'), lift); g.uniform1f(U('S'), .66);
      g.uniform3f(U('O'), W * .5, H * .71, 0); g.uniform2f(U('PO'), W * .5, H * .35); g.uniform2f(U('size'), W, H);
      g.drawElements(g.TRIANGLES, idx.length, g.UNSIGNED_SHORT, 0);
    };
    })();
    
    // a damped spring from "from" to "to" that starts with velocity v, solved exactly so it never drifts
    function spring(from, to, v, z, response) {
    return { from, to, v, z, w: 2 * Math.PI / response, t0: performance.now() };
    }
    function springAt(s, t) {
    const e0 = s.from - s.to;
    if (s.z >= 1) return s.to + (e0 + (s.v + s.w * e0) * t) * Math.exp(-s.w * t);
    const wd = s.w * Math.sqrt(1 - s.z * s.z), b = (s.v + s.z * s.w * e0) / wd;
    return s.to + Math.exp(-s.z * s.w * t) * (e0 * Math.cos(wd * t) + b * Math.sin(wd * t));
    }
    const val = (s, now) => springAt(s, (now - s.t0) / 1000);
    const digit = w => wrap10(Math.round(w.pos));
    const project = v => v * FRICTION / (1 - FRICTION) / 1e3;
    
    // let go: the flick decides where the wheel will stop
    function release(w, v) {
    const to = w.pos + project(v);
    const land = Math.round(to);
    roll(w, land, v);
    }
    function roll(w, to, v = 0, z = DAMPING) {
    if (still()) { w.pos = to; w.v = 0; w.s = null; rest(w); return; }
    w.s = spring(w.pos, to, v, z, Math.min(1, .3 + Math.abs(to - w.pos) * .035));
    run();
    }
    function rest(w) {
    w.el.setAttribute('aria-valuenow', digit(w));
    draw(w);
    check();
    }
    
    // the drum turns, every face is shaded by how far it faces away, a fast roll softens the digits
    function draw(w) {
    const shown = w.pos - .06 * Math.sin(2 * Math.PI * w.pos) / (2 * Math.PI);
    w.drum.style.transform = `${w.base} rotateX(${(shown * 36).toFixed(3)}deg)`;
    const b = still() ? 0 : Math.min(2.2, Math.abs(w.v) / 12);
    w.faces.forEach((f, i) => {
      let a = ((shown - i) * 36) % 360; if (a > 180) a -= 360; if (a < -180) a += 360;
      f.style.setProperty('--shade', (1 - Math.max(0, Math.cos(a * Math.PI / 180)) * .9).toFixed(3));
      f.style.filter = b > .3 ? `blur(${b.toFixed(2)}px)` : '';
    });
    }
    
    // For a real sale ask your server instead and let it send the coupon back, for example
    // return fetch('/api/unlock', { method: 'POST', body: code.join('') }).then(r => r.ok);
    async function isRight(code) {
    const ok = (n, i) => n === COMBO[i];
    return code.every(ok);
    }
    async function check() {
    if (open || closing || wheels.some(w => w.s || w.drag)) return;
    if (await isRight(wheels.map(digit))) openShackle();
    }
    
    // the shackle pops, clears the holes and swings round its long leg, the coupon slides out
    const sh = { lift: spring(0, 0, 0, 1, .3), turn: spring(0, 0, 0, 1, .6), tiltX: spring(0, 0, 0, 1, .4), tiltY: spring(0, 0, 0, 1, .4), turnAt: 0, dropAt: 0 };
    function openShackle() {
    open = true;
    const now = performance.now();
    gate.classList.add('open');
    if (still()) { sh.lift = spring(34, 34, 0, 1, .3); sh.turn = spring(-70, -70, 0, 1, .6); drawLock(now); return; }
    sh.lift = spring(0, 34, 0, .5, .32);
    sh.turnAt = now + 170;
    sh.tiltX = spring(val(sh.tiltX, now), 0, -40, .45, .3);
    run();
    }
    // closing swings it back, drops it into the holes with a knock, then rolls every wheel back to 0
    function closeShackle() {
    open = false; closing = true;
    const now = performance.now();
    gate.classList.remove('open');
    if (still()) {
      sh.lift = spring(0, 0, 0, 1, .3); sh.turn = spring(0, 0, 0, 1, .6); sh.turnAt = 0; closing = false;
      wheels.forEach(w => { w.pos = Math.round(w.pos) + (10 - digit(w)) % 10; w.s = null; rest(w); });
      drawLock(now); return;
    }
    sh.turn = spring(sh.turnAt ? 0 : val(sh.turn, now), 0, 0, .82, .5); sh.turnAt = 0;
    sh.dropAt = now + 330;
    run();
    }
    function scramble() {
    wheels.forEach((w, i) => setTimeout(() => roll(w, Math.round(w.pos) + (10 - digit(w)) % 10 + 10, 14, .9), i * 70));
    setTimeout(() => { closing = false; }, 900);
    }
    function drawLock(now) {
    if (sh.turnAt && now >= sh.turnAt) { sh.turn = spring(0, -70, 0, .72, .62); sh.turnAt = 0; }
    if (sh.dropAt && now >= sh.dropAt) {
      sh.lift = spring(val(sh.lift, now), 0, -60, .6, .2); sh.dropAt = 0;
      sh.tiltX = spring(val(sh.tiltX, now), 0, 60, .4, .25);
      setTimeout(scramble, 180);
    }
    const drag = wheels.find(w => w.drag), rx = -18 + val(sh.tiltX, now), ry = 24 + val(sh.tiltY, now);
    lock.style.transform = `rotateX(${rx.toFixed(3)}deg) rotateY(${ry.toFixed(3)}deg) scale(.66)`;
    const lift = val(sh.lift, now);
    if (steel) steel(rx, ry, lift, val(sh.turn, now));
    shackle.style.transform = `translate3d(-100px, ${(-243 - lift).toFixed(2)}px, 0) rotateY(${val(sh.turn, now).toFixed(2)}deg)`;
    // the legs end where the top face is, wherever the shackle has risen to, so they always sink into the holes
    shackle.style.clipPath = `inset(-20px -20px ${(82 - lift).toFixed(2)}px -20px)`;
    return drag;
    }
    
    // while you drag a wheel the whole lock leans a little under your finger, then springs back
    function lean(w, now) {
    const to = w ? { x: Math.max(-4, Math.min(4, (w.pos - w.drag.pos) * 2)), y: (wheels.indexOf(w) - 1) * -3 } : { x: 0, y: 0 };
    if (to.x !== sh.tiltX.to && !open) sh.tiltX = spring(val(sh.tiltX, now), to.x, 0, 1, .35);
    if (to.y !== sh.tiltY.to) sh.tiltY = spring(val(sh.tiltY, now), to.y, 0, 1, .35);
    }
    
    function frame(now) {
    let moving = false;
    for (const w of wheels) {
      if (w.drag) { moving = true; draw(w); continue; }
      if (!w.s) continue;
      const p = springAt(w.s, (now - w.s.t0) / 1000);
      w.v = (p - w.pos) / Math.max(.001, (now - (w.last || now - 16)) / 1000); w.last = now;
      w.pos = p;
      if (Math.abs(p - w.s.to) < .02 && Math.abs(w.v) < .5) { w.pos = w.s.to; w.v = 0; w.s = null; w.last = 0; rest(w); }
      else { moving = true; draw(w); }
    }
    lean(wheels.find(w => w.drag), now);
    drawLock(now);
    const settling = sh.turnAt || sh.dropAt || [sh.lift, sh.turn, sh.tiltX, sh.tiltY].some(s => Math.abs(val(s, now) - s.to) > .01);
    if (moving || settling) requestAnimationFrame(frame); else running = false;
    }
    function run() { if (!running) { running = true; requestAnimationFrame(frame); } }
    
    // drag 1:1, the last 80 ms of movement become the flick
    wheels.forEach(w => {
    w.el.addEventListener('pointerdown', e => {
      if (open || closing) return;
      e.stopPropagation();
      try { w.el.setPointerCapture(e.pointerId); } catch {}
      w.s = null;
      w.drag = { y: e.clientY, pos: w.pos, moved: false, trail: [[performance.now(), w.pos]] };
      run();
    });
    w.el.addEventListener('pointermove', e => {
      if (!w.drag) return;
      const dy = w.drag.y - e.clientY;
      if (Math.abs(dy) > 4) w.drag.moved = true;
      w.pos = w.drag.pos + dy / FACE;
      const now = performance.now();
      w.drag.trail.push([now, w.pos]);
      while (w.drag.trail.length > 2 && now - w.drag.trail[0][0] > 80) w.drag.trail.shift();
    });
    const up = () => {
      if (!w.drag) return;
      const d = w.drag, [t0, p0] = d.trail[0], now = performance.now();
      w.drag = null;
      if (!d.moved) { roll(w, Math.round(w.pos) + 1, 0, .8); return; }
      const v = now - t0 > 5 ? (w.pos - p0) / ((now - t0) / 1000) : 0;
      release(w, v);
    };
    w.el.addEventListener('pointerup', up);
    w.el.addEventListener('pointercancel', up);
    w.el.addEventListener('wheel', e => { e.preventDefault(); if (!open && !closing) roll(w, Math.round(w.s ? w.s.to : w.pos) + Math.sign(e.deltaY), 0, .8); }, { passive: false });
    w.el.addEventListener('keydown', e => {
      const step = { ArrowUp: 1, ArrowDown: -1 }[e.key];
      if (!step || open || closing) return;
      e.preventDefault();
      roll(w, Math.round(w.s ? w.s.to : w.pos) + step, 0, .9);
    });
    draw(w);
    });
    gate.querySelector('.stage').addEventListener('click', () => { if (open) closeShackle(); });
    gate.querySelector('.coupon button').addEventListener('click', async e => {
    try { await navigator.clipboard.writeText(REWARD); e.target.textContent = 'Copied'; } catch { e.target.textContent = REWARD; }
    });
    drawLock(performance.now());

Подключение к серверу

Сейчас код проверяется прямо в браузере, и его может увидеть любой. Для настоящей акции проверяйте код на сервере внутри isRight(), пример запроса стоит прямо над ней, и пусть сервер возвращает купон.

Полезно знать

Tilda, Webflow, WordPress

Нажмите «Скопировать весь код» вверху и вставьте его в один HTML-блок.

Tilda

Добавить блок, Другое, T123 HTML-код. Вставьте и сохраните. Проверяйте на опубликованной странице, в редакторе скрипты не запускаются.

Webflow

Панель Add, Embed. Вставьте и нажмите Save & Close. Свой код работает на опубликованном сайте.

WordPress

Добавить блок, Произвольный HTML. Вставьте и нажмите «Обновить».

Ещё в разделе «Коды и PIN»

Все
Скопировано