UICraft / Craft
SVGTear-off Ticket

How Tear-off Ticket works

Pull the corner of a cinema ticket and its perforations give way one by one, with a papery crackle. The stub drops into a pile, the rest of the ticket falls after it, and a different ticket springs into place.

Demo
UICRAFT PICTURE HOUSEBOX OFFICEMIDNIGHT SCREENING00:00ROW C · SEAT 12NO. 0042AFTERDARKADMITONE
Pull the top-right corner

How it works

1. Draw a flat ticket

Start with a rectangle, some text, and two colors. The outer <svg> is the drawing area. Its viewBox has four numbers. The first two start the coordinate system at the top-left corner, and the last two make the drawing 640 units wide and 332 units tall. The browser can shrink the whole drawing on a phone while keeping those coordinates the same.

<svg viewBox="0 0 640 332" width="100%">
  <rect x="52" y="74" width="488" height="178" fill="#f6e5b5" />
  <rect x="380" y="74" width="160" height="178" fill="#f3bd63" />
  <text x="76" y="158" font-size="51">AFTER</text>
  <text x="76" y="202" font-size="51">DARK</text>
</svg>

The ticket starts at y = 74 and ends at y = 252. The two paper colors meet at x = 380. That is where the tear will run.

2. Punch holes in the paper

An SVG mask controls how visible a drawing is. In this mask, white keeps the paper visible and black makes it transparent. Draw the ticket outline in white, then put a small black ellipse at each perforation. The background will show through every hole. A <defs> element stores the mask and the artwork for later use. You can draw the stored artwork with <use href="#artwork">.

<mask id="paper" maskUnits="userSpaceOnUse" x="0" y="0" width="640" height="332">
  <path fill="white" d={outline} />
  {FRAY.slice(1).map((_, index) => (
    <ellipse key={index} cx={SEAM} cy={TOP + (index + 1) * STEP}
      rx="1.7" ry="2.7" fill="black" />
  ))}
</mask>

maskUnits="userSpaceOnUse" gives the mask bounds the same coordinates as the drawing. The live component uses React’s useId() to give each mask, clip path, and drawing its own ID, so two tickets on the same page can work independently.

3. Cut one drawing into three pieces

A <clipPath> is a hard boundary. You see the part of the artwork inside the boundary. The clip path for the large piece follows the tear down, then wraps around the left edge. The lifted part of the stub follows the same tear, then wraps around the right edge. A rectangle keeps the lower stub attached from the current tear tip downward.

<clipPath id={`${id}-main`}>
  <path d={`${cut} V ${BOTTOM} H 0 V ${TOP} Z`} />
</clipPath>
<clipPath id={`${id}-attached`}>
  <rect x={SEAM} y={tip} width={WIDTH - SEAM} height={BOTTOM - tip} />
</clipPath>
<clipPath id={`${id}-peeled`}>
  <path d={`${cut} H ${WIDTH} V ${TOP} Z`} />
</clipPath>

V draws a vertical line, H draws a horizontal line, and Z closes the shape. Give each <use> one of these clips. With the three copies in the same position, the ticket still looks like one piece. Because both torn edges use cut, their shapes match.

4. Make the tear catch and snap

Keep progress between 0 and 1. Multiply it by the number of perforations to find which one is next. Math.floor() gives the number already broken. Between two holes, the tip creeps just 30% of the way to the next hole, then jumps the rest of the way when that perforation gives.

Real paper never tears in a straight line. Between each pair of holes, the edge passes through three extra points: a big sideways offset from FRAY in the middle and two smaller ones from grain(). grain() uses Math.sin() as a repeatable scribble, so the edge has the same shape on every render.

const grain = (n: number) => Math.sin(n * 91.7) * 1.1;

const edge = FRAY.slice(0, opened).map((offset, index) => {
  const y = TOP + index * STEP;
  return `L ${SEAM + grain(index * 3 + 1)} ${y + STEP * 0.25} `
    + `L ${SEAM + offset} ${y + STEP * 0.5} `
    + `L ${SEAM + grain(index * 3 + 2)} ${y + STEP * 0.75} L ${SEAM} ${y + STEP}`;
}).join(" ");
const cut = `M ${SEAM} ${TOP} ${edge} L ${SEAM} ${tip}`;

Draw cut twice along each torn edge. A wide, pale, dotted stroke looks like loose paper fibers. A thin solid stroke on top marks the edge itself.

<path d={cut} stroke="#fff6dc" strokeWidth="2.4" strokeDasharray=".3 1.4" />
<path d={cut} stroke="#b98a58" strokeWidth=".8" />

An SVG matrix() transform can move each point by a different amount. This one adds SKEW × (tip − y) to each x-coordinate in the lifted piece. At the tip the shift is zero. Higher up, it is larger. This holds the two stub pieces together at the tip while the top corner pulls away.

<g transform={`matrix(1 0 ${-SKEW} 1 ${SKEW * tip} 0)`}>
  <use href={artwork} clipPath={url("peeled")} />
</g>

Two small details sell the tension. A short gradient (crease) darkens the attached stub just below the tip, where the paper bends. And every time opened changes, React’s key={opened} remounts the stub’s wrapper. That replays a 150 ms CSS animation that starts the stub 2.5 units to the right and lets it settle back, so each perforation gives a tiny jolt as it breaks.

.tear-ticket-snap { animation: tear-ticket-snap 150ms cubic-bezier(.2,.8,.3,1); }
@keyframes tear-ticket-snap { from { transform: translate(2.5px, -1.5px); } }

5. Pull with a mouse, finger, or pen

Pointer events give mice, fingers, and pens the same set of handlers. clientX measures the pointer from the left side of the browser window in CSS pixels. getBoundingClientRect() gives the SVG’s on-screen width in the same units. Divide 640 by that width to convert a pixel of travel into SVG drawing units.

Call setPointerCapture() on press so the corner keeps receiving events when the pointer leaves it. touch-action: none on the corner tells the browser that the drag belongs to the ticket, so a touch there can tear the paper. A React ref remembers the starting x-position, progress, and pointer ID between events.

const next = start.progress + (event.clientX - start.x) * start.unitsPerPixel / PULL_DISTANCE;
setPulled((current) => Math.max(current, Math.min(1, next)));

Math.max() keeps broken perforations open even if the pointer travels backward. The pointerup, pointercancel, and lostpointercapture handlers clear the remembered pointer. A later pull picks up where the earlier one stopped.

6. Hold the stub, then let go

When next reaches 1, the last perforation is gone. Remember where the pointer was at that moment as anchor. From then on, the stub follows the pointer in both directions, so you can hold the torn piece in the air.

if (next >= 1 && !start.anchor) start.anchor = { x: event.clientX, y: event.clientY };
if (start.anchor) {
  setHeld({
    x: (event.clientX - start.anchor.x) * start.unitsPerPixel,
    y: (event.clientY - start.anchor.y) * start.unitsPerPixel,
  });
}

To throw the stub, we need the pointer’s speed when you let go. Each move stores a sample with event.timeStamp, which is a time in milliseconds. On release, compare the last sample with the oldest one from the final 90 ms. Distance divided by time gives a velocity in drawing units per second.

const last = start.samples[start.samples.length - 1];
const first = start.samples.find((sample) => last.t - sample.t < 90) ?? last;
const seconds = (last.t - first.t) / 1000;
const speed = (axis: "x" | "y") => (last[axis] - first[axis]) * start.unitsPerPixel / seconds;

release() stores the stub’s position, the velocity, the old ticket number, and the start time in fall. It also resets pulled to 0, increases serial so the next ticket is ready underneath, and adds the torn stub to pile.

7. Drop the stub into a pile

Think of the space under the ticket as a table seen from above. A falling stub moves away from you, so it shrinks to 42% of its size as it drops, and it ends up lying on the table with the other stubs. To make room for the pile, the live component’s viewBox is 470 units tall instead of 332.

restFor() picks the stub’s resting place: a spot under the ticket, an angle, and whether it lands printed side up. It nudges the spot in the direction you threw. Every choice comes from hash(serial, n), a tiny function that turns two numbers into a repeatable value between 0 and 1. The same ticket number always lands the same way.

const hash = (a: number, b: number) => {
  const value = Math.sin(a * 127.1 + b * 311.7) * 43758.5453;
  return value - Math.floor(value);
};

stubLanding(t) has to start at the throw and finish exactly on that spot after LAND (0.75) seconds. The motion uses a constant acceleration, like gravity. The usual formula is position = start + speed × t + ½ × acceleration × t². We know the start, the throw speed, the finish, and the time, so we solve for the acceleration that makes the path end on target:

const ax = 2 * (rest.x - STUB_X - release.x - release.vx * LAND) / LAND ** 2;
const ay = 2 * (rest.y - STUB_Y - release.y - release.vy * LAND) / LAND ** 2;
x = release.x + release.vx * time + 0.5 * ax * time ** 2 + sway * 14;
y = release.y + release.vy * time + 0.5 * ay * time ** 2;

A sine wave adds a little side-to-side sway, like paper in the air, and fades to zero by the time the stub lands. p is the fraction of the fall completed, from 0 to 1. Smoothstep, p × p × (3 − 2p), starts and ends gently, so the shrink and the straightening of the skew both use it.

The stub also tumbles. Math.cos() becomes a horizontal scale(). Near zero, the paper is edge-on. Below zero, it has flipped over, so a plain rectangle in the theme’s back color covers the print, because the back of a ticket is blank. A stub that lands face up turns a full 360°, and one that lands face down turns 180°. brightness() darkens the paper as it turns away from the light, and the drop shadow tightens as the stub gets closer to the table.

flip: Math.cos(Math.PI * (rest.faceUp ? 2 : 1) * out),

After it lands, the stub is drawn from pile with the same transform and its final values. The pile keeps the last 10 stubs. Each stub keeps its own copy of the artwork (stub-<number>), so its number and colors never change.

A beat after the stub, bodyFall() lets the rest of the ticket go. It speeds up as it falls (900 × s²), tips slightly to the left, shrinks, and fades out. The SVG has overflow: visible, so it can fall past the bottom of the drawing.

8. Bring in a different ticket

The artwork is a function of the ticket number. themeFor(serial) cycles through four films, each with a title, a showtime, two paper colors, and an emblem (moon, sea, star, or sun). seatFor() and barcodeFor() use hash() again, so every ticket has its own row, seat, and barcode, and they stay the same every time that ticket is drawn.

export const themeFor = (serial: number) => THEMES[(serial - FIRST_SERIAL) % THEMES.length];

A requestAnimationFrame() loop runs only while fall is set. It stores each frame’s timestamp in now, and the elapsed time drives the falling pieces and the new ticket.

After NEXT_DELAY (half a second), ticketEnter() drops the new ticket in from 80 units above. A damped spring, e^(−7t) × cos(11t), overshoots slightly, then settles. The ticket fades in over the first 0.16 seconds and tilts a little as it lands.

export function ticketEnter(t: number) {
  if (t <= 0) return { y: -80, rotate: 0, opacity: 0 };
  const decay = Math.exp(-7 * t);
  return { y: -80 * decay * Math.cos(11 * t), rotate: -2.5 * decay * Math.sin(11 * t), opacity: clamp(t / 0.16) };
}

When the spring has settled, the loop clears fall and stops. The corner can be pulled again.

9. Make paper sounds without audio files

The Web Audio API builds sound from connected nodes. Start with one second of white noise, which is random numbers between −1 and 1. Tearing paper sounds like short bursts of that noise.

noise = context.createBuffer(1, context.sampleRate, context.sampleRate);
const samples = noise.getChannelData(0);
for (let i = 0; i < samples.length; i++) samples[i] = Math.random() * 2 - 1;

Each burst plays the noise through a BiquadFilter and a Gain node. A band-pass filter keeps only the frequencies near frequency (higher sounds crisper). The gain ramps up in 4 ms and dies away exponentially, so you hear a click instead of a hiss. context.currentTime + delay schedules a sound ahead of time, with audio-clock precision.

gain.gain.setValueAtTime(0.0001, at);
gain.gain.exponentialRampToValueAtTime(volume, at + 0.004);
gain.gain.exponentialRampToValueAtTime(0.0001, at + length);
source.connect(filter).connect(gain).connect(context.destination);

A perforation is three high crackles a few milliseconds apart, with random pitch and volume, so no two sound alike. The last one is a louder rip of seven crackles. When a stub lands, a low-pass filter turns the noise into a soft thud, scheduled LAND seconds after release. A quieter tap plays when the new ticket arrives.

hear() runs wherever progress changes. It plays a crackle only when the number of broken holes goes up, and a ref remembers the last count, so each hole plays only once.

Browsers only allow audio after the visitor has interacted with the page, so paper.unlock() creates the AudioContext on the first press or click. The Sound button uses aria-pressed to show whether sound is on, so screen readers announce it as a toggle.

10. Make the button do the same tear

The Tear ticket button uses the same progress value. requestAnimationFrame() calls a function just before the browser paints. Subtract the start time from its timestamp to get the elapsed time in milliseconds, then turn that into a fraction of the animation. When the fraction reaches 1, the button calls release() with a gentle toss.

const start = performance.now();
const duration = 680 * (1 - progress);
function advance(now: number) {
  const amount = Math.min(1, (now - start) / duration);
  const value = progress + (1 - progress) * amount;
  hear(value);
  setPulled(value);
  frame.current = amount < 1 ? requestAnimationFrame(advance) : 0;
  if (amount === 1) release({ x: 12, y: -5 }, 160, -240);
}
frame.current = requestAnimationFrame(advance);

cancelAnimationFrame() clears the pending callback if the component is removed.

A native button works with Enter and Space. A polite live region says when the stub is torn off and names the next ticket. The SVG’s label describes the current ticket and how many stubs are in the pile. matchMedia() checks the system’s reduced-motion preference. With reduced motion on, release() puts the stub straight into the pile and swaps in the next ticket at once. The CSS prefers-reduced-motion query also turns off the perforation jolt.