mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-10-30 09:16:55 +00:00
feat(registry): blur every transform driver, and ship the reference case as shutter-slam (#4038)
The motion-blur snippet integrated translation only. Its output stage was one SVG filter per target whose copies were feOffset, and feOffset only translates, so a beat that only scaled or only turned sampled a displacement of zero and rendered sharp. No SVG filter primitive can give a copy its own affine transform, so the sampling loop was never the problem: the output stage was. Copies are now DOM clones of the element in an isolation:isolate group, each at 1/N opacity with mix-blend-mode plus-lighter, each carrying the element's resolved transform at its sample time. plus-lighter adds premultiplied colour, so N + 1 copies at 1/N sum to the average the shutter integral asks for; the isolation is load-bearing rather than tidy, because without a transparent backdrop of its own the first copy adds onto the page and blows a light background out to white. Reading the resolved matrix instead of a list of named GSAP properties is what makes every driver work at once: translation, scale, rotation, 3D rotation and skew arrive in the same one value. Measured against the After Effects export the shutter model was fitted to, per beat, previous stage to this one: scale +0.62 dB, rotate X +0.43, rotate Y +0.84, rotate Z +1.15, translate X -0.18, translate Y -0.04. The two small translate regressions are inherent and not tunable: the filter offset one rasterisation so every copy was pixel-identical, where each copy is now rasterised independently at its own fractional transform with its own subpixel antialiasing. Three consequences of the new stage, each carrying its own fix: - mix-blend-mode flattens preserve-3d, so a copy cannot inherit the parent's 3D context. Each copy carries the parent's perspective as its own first transform function instead. - A copy is styled by nothing that selected the original, since dropping the id also drops every #id rule that gave it size, colour and font. Each copy carries its own resolved style inline, read once and replayed. Those values are px, so a container-relative element needs them again when its box changes: a ResizeObserver re-snapshots rather than paying a subtree walk every frame. - A beat that moved and faded at once kept a full-strength smear behind a vanishing element. The element's opacity now rides the group; the 1/N weight stays on the copies. The axis option is gone. It selected which of x and y to sample, a question the resolved matrix does not have. shutter-slam is the new component: one word through six single-property beats, two translate slams, a scale punch, then a full turn about each axis, which exercises every driver the model covers in one mount. Easing is power2.inOut because it measured best, not because it was the default. A bezier fitted to the reference's own bbox centres looks like the better curve and renders worse: a blurred bbox centre is the shutter window's average rather than the instant, so on an accelerating segment the fit measures its own blur. Co-authored-by: Miguel Ángel <miguel.sierra@heygen.com>
This commit is contained in:
co-authored by
Miguel Ángel
parent
a8a9fdb0fe
commit
82f49262ec
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Motion Blur"
|
||||
description: "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight SVG copies along the real trajectory"
|
||||
description: "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight additive copies of the element along its real trajectory, so translation, scale, rotation, 3D rotation and skew all drive the smear"
|
||||
---
|
||||
|
||||
import { InstallCommand } from "/snippets/install-command.jsx";
|
||||
@@ -35,22 +35,31 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
|
||||
1. After every timeline update (each rendered frame), the snippet seeks
|
||||
the timeline to `samplesPerFrame` sub-frame times spread evenly across
|
||||
the shutter window, reads each target's GSAP x/y at every sample, then
|
||||
restores the frame time. Seeks run with events suppressed, so no user
|
||||
callbacks fire and the DOM ends up exactly where the frame left it.
|
||||
2. An SVG filter stacks one copy of the element per sample (feOffset to
|
||||
the sampled position relative to the current one) and adds them at
|
||||
equal weight (feComposite arithmetic, 1/N each, sRGB space). Result:
|
||||
a box smear along the actual trajectory whose length is speed ×
|
||||
shutter time, with no decaying one-sided trail. The tails — where
|
||||
fewer copies overlap — step down evenly at 1/N per copy; wherever the
|
||||
element travels less than its own size the copies pile up past 1 and
|
||||
clamp, so the middle of the smear is solid rather than a plateau.
|
||||
3. The element itself is then composited over that smear, sharp and at
|
||||
full opacity. No single duplicate ever exceeds 1/N, so a moving edge
|
||||
resolves as a staircase of ghosts behind a solid frame-time instance.
|
||||
4. When the sampled positions collapse to the current one (element at
|
||||
rest), the filter is removed so the element renders sharp.
|
||||
the shutter window, reads each target's RESOLVED `transform` at every
|
||||
sample, then restores the frame time. Seeks run with events suppressed,
|
||||
so no user callbacks fire and the DOM ends up exactly where the frame
|
||||
left it. Reading the resolved matrix rather than a list of named GSAP
|
||||
properties is what makes every driver work: translation, scale,
|
||||
rotation, 3D rotation and skew arrive in the same one value, and a
|
||||
driver nobody thought of needs no change here.
|
||||
2. One copy of the element per sample is stacked in an isolated group,
|
||||
each carrying its sample's transform, each at 1/N opacity with
|
||||
`mix-blend-mode: plus-lighter`. plus-lighter adds premultiplied colour,
|
||||
so N+1 copies at 1/N sum to the average — the shutter integral. The
|
||||
isolation is load-bearing: without a transparent backdrop of its own
|
||||
the first copy would add onto the page and blow a light background out
|
||||
to white. Result: a smear along the actual trajectory whose extent is
|
||||
speed × shutter time, with no decaying one-sided trail. The tails —
|
||||
where fewer copies overlap — step down evenly at 1/N per copy; wherever
|
||||
the element travels less than its own size the copies pile up past 1
|
||||
and clamp, so the middle of the smear is solid rather than a plateau.
|
||||
3. The element itself paints over that group, sharp and at full opacity.
|
||||
No single copy ever exceeds 1/N, so a moving edge resolves as a
|
||||
staircase of ghosts behind a solid frame-time instance. The group
|
||||
carries the element's own opacity, so a beat that moves and fades at
|
||||
once fades its smear with it.
|
||||
4. When every sampled transform collapses to the current one (element at
|
||||
rest), the group is hidden so the element renders sharp.
|
||||
|
||||
Shutter window (AE semantics, per frame at time t, frame interval 1/fps):
|
||||
shutterTime = shutterAngle / 360 / fps
|
||||
@@ -71,9 +80,23 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
instance on top is what keeps total ink above the unblurred frame's.
|
||||
|
||||
Requirements:
|
||||
- Elements must be animated via GSAP x/y (transform), not left/top. The
|
||||
element's own scale/rotation is compensated; skew, 3D rotation and
|
||||
transformed ancestors are not.
|
||||
- Elements must be animated via `transform` (GSAP x/y/scale/rotation and the
|
||||
3D and skew properties all qualify), not left/top. Transformed ancestors
|
||||
are still not compensated.
|
||||
- A 3D beat reads its perspective off the element's parent and applies it per
|
||||
copy, so the vanishing point follows each copy's transform-origin rather
|
||||
than the parent's perspective-origin. Those agree when the element is
|
||||
centred in its perspective parent, which is how a 3D beat is authored.
|
||||
- A copy drops the element's id but keeps its classes, because a class rule is
|
||||
the only thing that can still style a copy's pseudo-elements. So a selector
|
||||
written against a class matches the copies too: after attaching, address the
|
||||
element by id or by reference, never by a class a copy also carries.
|
||||
- A target is blurred once: a second attachMotionBlur() call naming the same
|
||||
element leaves the first call's copies in place rather than stacking a
|
||||
second set over them.
|
||||
- Cost is N + 1 copies of the target's whole subtree, restyled on attach and
|
||||
on resize and re-transformed every frame. Point it at the element that
|
||||
moves, not at a container holding it.
|
||||
- The host must render the timeline for the blur to update — HyperFrames
|
||||
seeks every frame. A fresh paused timeline that is never seeked shows no
|
||||
blur on its first frame.
|
||||
@@ -96,12 +119,12 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
fps — composition frame rate (default: the root's data-fps,
|
||||
else 30). Pass it explicitly when rendering with an
|
||||
fps override (`hyperframes render --fps`).
|
||||
axis — "x" | "y" | "both" (default "both")
|
||||
-->
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
@@ -120,9 +143,55 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// objectBoundingBox percentage for a px offset plus padding.
|
||||
function regionPercent(offset, size, padPercent) {
|
||||
return ((offset / size) * 100 + padPercent).toFixed(2) + "%";
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
@@ -133,49 +202,7 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var axis = opts.axis || "both";
|
||||
var fps = resolveFps(opts.fps);
|
||||
var useX = axis !== "y";
|
||||
var useY = axis !== "x";
|
||||
|
||||
// Untransformed box size; SVG elements have no offsetWidth, so use the
|
||||
// same bbox GSAP uses to resolve their percent transforms.
|
||||
function boxSize(el, horizontal) {
|
||||
var box = typeof el.offsetWidth === "number" ? el : el.getBBox ? el.getBBox() : null;
|
||||
var size = box
|
||||
? horizontal
|
||||
? box.offsetWidth || box.width
|
||||
: box.offsetHeight || box.height
|
||||
: 0;
|
||||
return size || el.getBoundingClientRect()[horizontal ? "width" : "height"] || 1;
|
||||
}
|
||||
|
||||
// GSAP x/y may carry a % unit and xPercent/yPercent is a separate term;
|
||||
// resolve both against the element's own box so samples are in px.
|
||||
function readAxis(el, prop, percentProp, size) {
|
||||
var px = parseFloat(gsap.getProperty(el, prop, "px")) || 0;
|
||||
var percent = parseFloat(gsap.getProperty(el, percentProp)) || 0;
|
||||
return px + (percent * size) / 100;
|
||||
}
|
||||
|
||||
function readPosition(el) {
|
||||
return {
|
||||
x: useX ? readAxis(el, "x", "xPercent", boxSize(el, true)) : 0,
|
||||
y: useY ? readAxis(el, "y", "yPercent", boxSize(el, false)) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// CSS filters run in the element's pre-transform space while GSAP x/y are
|
||||
// post-transform, so a displacement is mapped through the inverse of the
|
||||
// element's own scale/rotation. Ancestor transforms are not compensated.
|
||||
function toFilterSpace(el, dx, dy) {
|
||||
var sx = parseFloat(gsap.getProperty(el, "scaleX")) || 1;
|
||||
var sy = parseFloat(gsap.getProperty(el, "scaleY")) || 1;
|
||||
var theta = ((parseFloat(gsap.getProperty(el, "rotation")) || 0) * Math.PI) / 180;
|
||||
var cos = Math.cos(theta);
|
||||
var sin = Math.sin(theta);
|
||||
return { dx: (dx * cos + dy * sin) / sx, dy: (-dx * sin + dy * cos) / sy };
|
||||
}
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
@@ -189,83 +216,103 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
var ns = "http://www.w3.org/2000/svg";
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var weight = String(1 / samples);
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// One SVG filter per target: N+1 offset copies of SourceGraphic added at 1/N
|
||||
// each, then the element itself over the top. Accumulating in sRGB matches
|
||||
// AE's default (non-linear) 8-bpc working space.
|
||||
var state = targets.map(function (el) {
|
||||
var uid = "hf-mb-" + window._hfMbUid++;
|
||||
var svg = document.createElementNS(ns, "svg");
|
||||
svg.setAttribute("style", "position:absolute;width:0;height:0;overflow:hidden;");
|
||||
|
||||
var filter = document.createElementNS(ns, "filter");
|
||||
filter.id = uid;
|
||||
filter.setAttribute("color-interpolation-filters", "sRGB");
|
||||
|
||||
var offsets = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var feOff = document.createElementNS(ns, "feOffset");
|
||||
feOff.setAttribute("in", "SourceGraphic");
|
||||
feOff.setAttribute("dx", "0");
|
||||
feOff.setAttribute("dy", "0");
|
||||
feOff.setAttribute("result", "s" + k);
|
||||
filter.appendChild(feOff);
|
||||
offsets.push(feOff);
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
|
||||
// Pairwise accumulation: the first composite scales both inputs by 1/N, every
|
||||
// later one adds the next copy at 1/N to the running sum. The N+1 weights total
|
||||
// (N+1)/N, so an element wider than its own smear saturates through the middle
|
||||
// and the filter clamps there. That is the saturation the reference shows, and
|
||||
// the sharp instance covers the same region regardless.
|
||||
var accumulated = "s0";
|
||||
for (var c = 1; c < copies; c++) {
|
||||
var feComp = document.createElementNS(ns, "feComposite");
|
||||
feComp.setAttribute("operator", "arithmetic");
|
||||
feComp.setAttribute("in", accumulated);
|
||||
feComp.setAttribute("in2", "s" + c);
|
||||
feComp.setAttribute("k1", "0");
|
||||
feComp.setAttribute("k2", c === 1 ? weight : "1");
|
||||
feComp.setAttribute("k3", weight);
|
||||
feComp.setAttribute("k4", "0");
|
||||
accumulated = "a" + c;
|
||||
feComp.setAttribute("result", accumulated);
|
||||
filter.appendChild(feComp);
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
|
||||
// The frame-time instance is drawn sharp, at full opacity, over the smear.
|
||||
// Every blurred copy stays at 1/N, so nothing but the instance the frame is
|
||||
// actually at reads as solid. Unnamed, so it is the filter output.
|
||||
var feOver = document.createElementNS(ns, "feComposite");
|
||||
feOver.setAttribute("operator", "over");
|
||||
feOver.setAttribute("in", "SourceGraphic");
|
||||
feOver.setAttribute("in2", accumulated);
|
||||
filter.appendChild(feOver);
|
||||
|
||||
svg.appendChild(filter);
|
||||
document.body.appendChild(svg);
|
||||
|
||||
return { el: el, offsets: offsets, filter: filter, filterId: uid, xs: [], ys: [] };
|
||||
});
|
||||
|
||||
// The element may carry its own inline filter (authored or tweened by
|
||||
// GSAP); the blur is appended to that chain and removed from it, never
|
||||
// written over it.
|
||||
var OWN_FILTER = /\s*url\(["']?#hf-mb-\d+["']?\)/g;
|
||||
|
||||
function baseFilter(el) {
|
||||
return el.style.filter.replace(OWN_FILTER, "").trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
function clearBlur(s) {
|
||||
s.el.style.filter = baseFilter(s.el);
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function") new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
@@ -273,7 +320,9 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(clearBlur);
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -283,15 +332,13 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read positions, then restore the frame time.
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
var pos = readPosition(s.el);
|
||||
s.xs[k] = pos.x;
|
||||
s.ys[k] = pos.y;
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
@@ -299,48 +346,42 @@ That writes one file: `compositions/components/motion-blur.html`.
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readPosition(s.el);
|
||||
var minDx = Infinity;
|
||||
var maxDx = -Infinity;
|
||||
var minDy = Infinity;
|
||||
var maxDy = -Infinity;
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
var d = toFilterSpace(s.el, s.xs[i] - current.x, s.ys[i] - current.y);
|
||||
var dx = d.dx;
|
||||
var dy = d.dy;
|
||||
s.offsets[i].setAttribute("dx", dx.toFixed(3));
|
||||
s.offsets[i].setAttribute("dy", dy.toFixed(3));
|
||||
if (dx < minDx) minDx = dx;
|
||||
if (dx > maxDx) maxDx = dx;
|
||||
if (dy < minDy) minDy = dy;
|
||||
if (dy > maxDy) maxDy = dy;
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Below half a pixel of smear the average is indistinguishable from
|
||||
// the source — render sharp instead of paying for the filter.
|
||||
if (maxDx - minDx < 0.5 && maxDy - minDy < 0.5) {
|
||||
clearBlur(s);
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// Grow the filter region to cover every copy AND the sharp instance the
|
||||
// final composite draws at offset 0 (objectBoundingBox units, 10% padding
|
||||
// so anti-aliased edges are not clipped). Clamping the bounds through 0
|
||||
// matters whenever the window sits entirely on one side of the frame time
|
||||
// — any shutterPhase above 0 or below -shutterAngle — because then no copy
|
||||
// is at 0 and a region derived from the copies alone cuts the instance off.
|
||||
var x0 = Math.min(0, minDx);
|
||||
var x1 = Math.max(0, maxDx);
|
||||
var y0 = Math.min(0, minDy);
|
||||
var y1 = Math.max(0, maxDy);
|
||||
var w = boxSize(s.el, true);
|
||||
var h = boxSize(s.el, false);
|
||||
s.filter.setAttribute("x", regionPercent(x0, w, -10));
|
||||
s.filter.setAttribute("width", regionPercent(x1 - x0, w, 120));
|
||||
s.filter.setAttribute("y", regionPercent(y0, h, -10));
|
||||
s.filter.setAttribute("height", regionPercent(y1 - y0, h, 120));
|
||||
var base = baseFilter(s.el);
|
||||
s.el.style.filter = (base ? base + " " : "") + "url(#" + s.filterId + ")";
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
@@ -403,7 +444,6 @@ tl.set(document.body, {}, DATA_DURATION);
|
||||
attachMotionBlur("#my-box", tl, {
|
||||
shutterAngle: 720, // degrees of the frame interval the shutter is open
|
||||
samplesPerFrame: 16, // sub-intervals of the window; 17 duplicates at 1/16 each
|
||||
axis: "x", // "x" | "y" | "both"
|
||||
});
|
||||
|
||||
window.__timelines = window.__timelines || {};
|
||||
@@ -414,14 +454,14 @@ window.__timelines["my-composition"] = tl;
|
||||
|
||||
This is the After Effects layer Motion Blur model — temporal supersampling — synthesised inside the page, because the renderer captures one instant per frame with no shutter.
|
||||
|
||||
1. **Sample the trajectory** — after every timeline seek, the snippet seeks the timeline (events suppressed) to one sub-frame time per window boundary, reads each target's GSAP `x`/`y`, then restores the frame time. The window is `shutterAngle / 360 / fps` seconds long and starts `shutterPhase / 360 / fps` seconds from the frame time; `samplesPerFrame` divides it into that many sub-intervals, so there are `samplesPerFrame + 1` samples and both ends of the window carry one.
|
||||
2. **Add the duplicates** — each target gets an SVG filter that stacks one `feOffset` copy of the element per sample at its sampled position and adds them at equal weight (`feComposite` arithmetic, 1/N each, sRGB). A solid translating at speed `v` becomes a box smear of length `v × shutterTime`, centred on its instantaneous position — no one-sided trail and no Gaussian halo. No single duplicate exceeds `1/N`, so the tails step down evenly; where the element travels less than its own size the copies overlap past 1 and clamp, leaving the middle solid rather than a plateau.
|
||||
1. **Sample the trajectory** — after every timeline seek, the snippet seeks the timeline (events suppressed) to one sub-frame time per window boundary, reads each target's resolved `transform` matrix, then restores the frame time. Reading the resolved matrix rather than a list of named GSAP properties is what makes every driver work: translation, scale, rotation, 3D rotation and skew all arrive in the same one value. The window is `shutterAngle / 360 / fps` seconds long and starts `shutterPhase / 360 / fps` seconds from the frame time; `samplesPerFrame` divides it into that many sub-intervals, so there are `samplesPerFrame + 1` samples and both ends of the window carry one.
|
||||
2. **Add the duplicates** — each target gets a group of DOM copies of itself, one per sample, each carrying that sample's transform at `1/N` opacity with `mix-blend-mode: plus-lighter`. plus-lighter adds premultiplied colour, so N + 1 copies at 1/N sum to the average, which is the shutter integral. The group sets `isolation: isolate`, and that is load-bearing rather than tidy: without a transparent backdrop of its own the first copy would add onto the page and blow a light background out to white. A solid translating at speed `v` becomes a box smear of length `v × shutterTime`, centred on its instantaneous position — no one-sided trail and no Gaussian halo. No single duplicate exceeds `1/N`, so the tails step down evenly; where the element travels less than its own size the copies overlap past 1 and clamp, leaving the middle solid rather than a plateau.
|
||||
3. **Composite the sharp instance on top** — the element is then drawn over the smear at full opacity, so the position the frame is actually at stays crisp and only the duplicates are faint. This is the single largest difference from a plain average, and the one that makes the result read like After Effects rather than like a long exposure.
|
||||
4. **Rest is sharp** — when the sampled positions collapse onto the current one, the filter is removed.
|
||||
4. **Rest is sharp** — when every sampled transform collapses onto the current one, the group is hidden and the element renders unblurred. The group also carries the element's own opacity, so a beat that moves and fades at once fades its smear with it.
|
||||
|
||||
The defaults come from measurement, not from the After Effects UI's nominal values. On a 1920×1080 / 30 fps export of translating text, the outermost duplicate on each side sits exactly one frame away from the frame time, with 8 evenly spaced duplicates between it and the centre — a 720° window at −360° phase, divided into 16. The staircase across a stroke steps by 0.063 ± 0.002 of the sharp text intensity per duplicate: flat 1/16, no taper toward the window edges. Replaying that export through this component scores 32.5 dB mean PSNR against it (min 27.6 over the 72 translating frames), against 24.2 dB (min 17.1) for the previous half-frame centred window.
|
||||
|
||||
Copies follow the real trajectory, so eased and curved motion smear correctly. The element's own scale and rotation are compensated when mapping the displacements into filter space; skew, 3D rotation and transformed ancestors are not. Only translation is integrated — rotation, scale or opacity changes within the shutter window are not blurred.
|
||||
Copies follow the real trajectory, so eased and curved motion smear correctly, and every property that reaches `transform` drives the smear on its own: a beat that only scales or only turns blurs exactly as a beat that only translates does. A 3D beat reads its perspective off the element's parent and applies it per copy, because `mix-blend-mode` flattens `preserve-3d` and a copy therefore cannot inherit the parent's 3D context. Transformed ancestors are still not compensated. A copy drops the element's id but keeps its classes, so after attaching, address the element by id or by reference rather than by a class the copies also carry.
|
||||
|
||||
## Options
|
||||
|
||||
@@ -429,9 +469,8 @@ Copies follow the real trajectory, so eased and curved motion smear correctly. T
|
||||
| --- | --- | --- |
|
||||
| `shutterAngle` | `720` | Degrees of the frame interval the shutter is open. `720` spans two frames, the width measured off the After Effects reference; `360` spans one; `0` disables the blur |
|
||||
| `shutterPhase` | `-360` | Degrees offset of the window start from the frame time. `-360` starts the window one frame back, which with a 720° angle centres it on the frame |
|
||||
| `samplesPerFrame` | `16` | Sub-intervals of the shutter window (2–64), so `N + 1` duplicates at `1/N` opacity each. More sub-intervals close the gaps between duplicates at high speed at a higher filter cost |
|
||||
| `samplesPerFrame` | `16` | Sub-intervals of the shutter window (2–64), so `N + 1` duplicates at `1/N` opacity each. More sub-intervals close the gaps between duplicates at high speed, at the cost of one more copy of the element per frame |
|
||||
| `fps` | root `data-fps`, else `30` | Composition frame rate. Pass it explicitly when rendering with an fps override (`hyperframes render --fps`) |
|
||||
| `axis` | `"both"` | Motion axis sampled — `"x"`, `"y"`, or `"both"` |
|
||||
|
||||
{/* hf:generated-footer */}
|
||||
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
---
|
||||
title: "Shutter Slam"
|
||||
description: "One word thrown through six single-property beats under integrated shutter blur — two translate slams, a scale punch, then a full turn about each axis — on the measured easing of the After Effects export the shutter model was fitted to"
|
||||
---
|
||||
|
||||
import { InstallCommand } from "/snippets/install-command.jsx";
|
||||
|
||||
## Install
|
||||
|
||||
<InstallCommand command="npx hyperframes add shutter-slam" item="shutter-slam" />
|
||||
|
||||
That writes one file: `compositions/components/shutter-slam.html`.
|
||||
|
||||
<iframe
|
||||
className="w-full aspect-video rounded-xl border-0 bg-zinc-100 dark:bg-zinc-800"
|
||||
title="shutter-slam preview"
|
||||
loading="lazy"
|
||||
srcDoc={`<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;height:100%;overflow:hidden;background:transparent}hyperframes-player{display:block;width:100%;height:100%}</style><script src="https://cdn.jsdelivr.net/npm/@hyperframes/player@latest/dist/hyperframes-player.global.js"><\/script></head><body><script>fetch("/public/catalog/components/shutter-slam.json").then(function(r){return r.json()}).then(function(d){var p=document.createElement("hyperframes-player");p.setAttribute("srcdoc",d.html);p.setAttribute("controls","");p.setAttribute("autoplay","");p.setAttribute("loop","");p.setAttribute("muted","");p.setAttribute("poster","https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shutter-slam.png");document.body.appendChild(p)});<\/script></body></html>`}
|
||||
/>
|
||||
|
||||
## Paste it into your composition
|
||||
|
||||
Open `compositions/components/shutter-slam.html` and copy what is inside into your own composition.
|
||||
|
||||
A component has no size or duration of its own. It takes both from the composition
|
||||
you paste it into.
|
||||
|
||||
## Source
|
||||
|
||||
<Accordion title="shutter-slam.html">
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<!--
|
||||
shutter-slam: HyperFrames video primitive
|
||||
|
||||
One word thrown through six single-property beats, every frame integrated
|
||||
over the camera shutter: two hard translate slams, a scale punch, then a
|
||||
full turn about each of the three axes. It is the motion-blur primitive's
|
||||
reference case — the beats are the ones measured off the After Effects
|
||||
export the shutter model was fitted to, so every driver the model covers
|
||||
(translate, scale, rotate, 3D rotate) is exercised in one mount.
|
||||
|
||||
Variables:
|
||||
text: the slammed word
|
||||
accent: green, blue, or violet word color
|
||||
blur: shutter (integrated) or none (one instant per frame)
|
||||
cues: comma seconds from mount start for each of the six beats
|
||||
exit: none, fade, or up
|
||||
|
||||
Envelope, fixed beats with elastic HOLD:
|
||||
BEATS = 5.97s at the authored rhythm (0.3s per slam, 0.6s per 3D turn,
|
||||
0.73s for the Z turn)
|
||||
HOLD = max(0, D - BEATS - OUT), the word at rest
|
||||
OUT = 0.40s when exit is fade or up, else 0
|
||||
If D is shorter than BEATS + OUT the beat clock compresses; the timeline
|
||||
is never time-scaled.
|
||||
|
||||
Easing is power2.inOut because it measured best, not because it was the
|
||||
default. A bezier fitted to the reference's own bbox centres looks like the
|
||||
better curve on paper and renders worse: 1.3 dB down on the horizontal slam,
|
||||
1.0 dB up on the vertical turn, 0.25 dB down over the clip. A blurred bbox
|
||||
centre is the shutter window's average, not the instant, so on an
|
||||
accelerating segment the fit is measuring its own blur.
|
||||
|
||||
Amplitudes are fractions of the host box (32.1cqw, 30.5cqh), so the slams
|
||||
leave the frame on a wide mount exactly as far as they do on the reference.
|
||||
The scale punch overflows on purpose; the clip crops it.
|
||||
|
||||
Mount contract: the runtime clones only this template. #root fills the host
|
||||
box, establishes the container query basis, and has no data-width or
|
||||
data-height. One paused timeline registers under the literal shutter-slam
|
||||
key.
|
||||
-->
|
||||
<html
|
||||
lang="en"
|
||||
data-composition-id="shutter-slam"
|
||||
data-composition-duration="6"
|
||||
data-composition-variables='[
|
||||
{ "id": "text", "type": "string", "role": "content", "label": "Word", "description": "The word driven through the six beats.", "default": "MOTION" },
|
||||
{ "id": "accent", "type": "enum", "role": "style", "label": "Accent", "description": "Word color.", "default": "green", "options": [{ "value": "green", "label": "Green" }, { "value": "blue", "label": "Blue" }, { "value": "violet", "label": "Violet" }] },
|
||||
{ "id": "blur", "type": "enum", "role": "motion", "label": "Blur", "description": "Integrate each frame over the shutter window, or capture one instant per frame.", "default": "shutter", "options": [{ "value": "shutter", "label": "Shutter" }, { "value": "none", "label": "None" }] },
|
||||
{ "id": "cues", "type": "string", "role": "motion", "label": "Cues", "description": "Comma seconds from mount start for each of the six beats; empty keeps the authored rhythm.", "default": "" },
|
||||
{ "id": "exit", "type": "enum", "role": "motion", "label": "Exit", "description": "How the word leaves.", "default": "none", "options": [{ "value": "none", "label": "None" }, { "value": "fade", "label": "Fade" }, { "value": "up", "label": "Up" }] }
|
||||
]'
|
||||
>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Shutter Slam</title>
|
||||
</head>
|
||||
<body>
|
||||
<template>
|
||||
<div id="root" data-composition-id="shutter-slam" data-duration="6" data-fps="30">
|
||||
<style>
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#root {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
container-type: size;
|
||||
isolation: isolate;
|
||||
font-family: var(--font-display, Inter, system-ui, sans-serif);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ss-clip {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100cqw;
|
||||
height: 100cqh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* The turns need a perspective ancestor, and the blur reads its
|
||||
perspective off the word's own parent, so the stage that carries
|
||||
it must be the word's direct parent. */
|
||||
.ss-stage {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
perspective: 104cqw;
|
||||
}
|
||||
|
||||
.ss-word {
|
||||
color: var(--ss-accent, #71f5a7);
|
||||
font-size: var(--ss-font-size, min(14cqw, 26cqh));
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
letter-spacing: -0.02em;
|
||||
white-space: nowrap;
|
||||
transform-origin: 50% 50%;
|
||||
will-change: transform;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div
|
||||
id="shutter-slam-clip"
|
||||
class="ss-clip clip"
|
||||
data-start="0"
|
||||
data-duration="6"
|
||||
data-track-index="0"
|
||||
>
|
||||
<div class="ss-stage">
|
||||
<div class="ss-word" id="shutter-slam-word" role="heading" aria-level="1"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
function resolveFps(optionFps) {
|
||||
var explicit = Number(optionFps);
|
||||
if (explicit > 0) return explicit;
|
||||
|
||||
var root = document.querySelector("[data-composition-id][data-fps]");
|
||||
var rootFps = root ? Number(root.getAttribute("data-fps")) : 0;
|
||||
if (rootFps > 0) return rootFps;
|
||||
|
||||
return 30;
|
||||
}
|
||||
|
||||
function numOption(value, fallback) {
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
opts = opts || {};
|
||||
var shutterAngle = numOption(opts.shutterAngle, 720);
|
||||
var shutterPhase = numOption(opts.shutterPhase, -360);
|
||||
var requestedSamples = numOption(opts.samplesPerFrame, 16);
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var fps = resolveFps(opts.fps);
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
if (typeof s === "string") {
|
||||
document.querySelectorAll(s).forEach(function (el) {
|
||||
acc.push(el);
|
||||
});
|
||||
} else if (s instanceof Element) {
|
||||
acc.push(s);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function")
|
||||
new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var t0 = tl.time();
|
||||
var duration = tl.duration();
|
||||
var windowStart = t0 + shutterPhase / 360 / fps;
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
tl.time(t0, true);
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
// tl.eventCallback("onUpdate") is unavailable under the HyperFrames runtime proxy, so a
|
||||
// tracker tween's onUpdate fires on every seek. Sampling is deferred to a microtask:
|
||||
// seeking GSAP from inside its own render reads stale tween state, while the microtask
|
||||
// runs after the seek returns and before the frame is captured or painted.
|
||||
var _proxy = { t: 0 };
|
||||
tl.to(
|
||||
_proxy,
|
||||
{
|
||||
t: 1,
|
||||
duration: Math.max(tl.duration(), 0.1),
|
||||
ease: "none",
|
||||
onUpdate: function () {
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
Promise.resolve().then(function () {
|
||||
scheduled = false;
|
||||
applyShutter();
|
||||
});
|
||||
},
|
||||
},
|
||||
0,
|
||||
);
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
<script>
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var root = document.getElementById("root");
|
||||
var word = root.querySelector(".ss-word");
|
||||
var vars =
|
||||
window.__hyperframes && window.__hyperframes.getVariables
|
||||
? window.__hyperframes.getVariables()
|
||||
: {};
|
||||
|
||||
var text = vars.text == null ? "MOTION" : String(vars.text);
|
||||
var accentColors = {
|
||||
green: "var(--brand, #71f5a7)",
|
||||
blue: "var(--accent, #61a8ff)",
|
||||
violet: "var(--accent-2, #b895ff)",
|
||||
};
|
||||
var accent = Object.prototype.hasOwnProperty.call(accentColors, vars.accent)
|
||||
? vars.accent
|
||||
: "green";
|
||||
var blurred = vars.blur !== "none";
|
||||
var exit = vars.exit === "fade" || vars.exit === "up" ? vars.exit : "none";
|
||||
|
||||
root.style.setProperty("--ss-accent", accentColors[accent]);
|
||||
word.textContent = text;
|
||||
|
||||
// One em per character keeps any word inside the box at rest, which is what
|
||||
// the slam amplitudes are measured against; the scale punch is meant to
|
||||
// overflow and the clip crops it.
|
||||
var fittedCqw = Math.min(14, 76 / Math.max(1, Array.from(text).length));
|
||||
root.style.setProperty("--ss-font-size", "min(" + fittedCqw.toFixed(3) + "cqw, 26cqh)");
|
||||
|
||||
// Measured best, not defaulted. A bezier fitted to the reference's own bbox
|
||||
// centres renders 0.25 dB worse over the clip, because a blurred bbox centre
|
||||
// is the shutter window's average rather than the instant. See the header.
|
||||
var EASE = "power2.inOut";
|
||||
var SLAM_X = 32.1; // cqw, the reference's 617 px on a 1920 px frame
|
||||
var SLAM_Y = 30.5; // cqh, its 329 px on a 1080 px frame
|
||||
var SLAM = 0.3;
|
||||
var TURN = 0.6;
|
||||
var TURN_Z = 0.733;
|
||||
// Authored start of each beat.
|
||||
var CUES_BASE = [0, 1.2, 2.4, 3.7, 4.5, 5.233];
|
||||
var BEATS_BASE = CUES_BASE[5] + TURN_Z;
|
||||
var OUT_BASE = exit === "none" ? 0 : 0.4;
|
||||
|
||||
var duration = Math.max(0.001, parseFloat(root.dataset.duration || "6"));
|
||||
var baseTotal = BEATS_BASE + OUT_BASE;
|
||||
var beatScale = duration < baseTotal ? duration / baseTotal : 1;
|
||||
|
||||
var slam = SLAM * beatScale;
|
||||
var turn = TURN * beatScale;
|
||||
var turnZ = TURN_Z * beatScale;
|
||||
var out = OUT_BASE * beatScale;
|
||||
// How long each beat runs, in beat order.
|
||||
var LENGTHS = [slam * 4, slam * 4, slam * 4, turn, turn, turnZ];
|
||||
|
||||
// An authored cue replaces the rhythm rather than scaling it, so a beat locked
|
||||
// to narration lands where the narration does. A missing or unreadable entry
|
||||
// keeps its authored start; one that would run its beat past the mount is
|
||||
// pulled back to end on the last frame, since past the end it never renders.
|
||||
var authored = String(vars.cues == null ? "" : vars.cues)
|
||||
.split(",")
|
||||
.map(function (part) {
|
||||
return parseFloat(part.trim());
|
||||
});
|
||||
var cues = CUES_BASE.map(function (base, index) {
|
||||
var value = authored[index];
|
||||
if (!Number.isFinite(value)) return base * beatScale;
|
||||
return Math.min(Math.max(value, 0), Math.max(0, duration - out - LENGTHS[index]));
|
||||
});
|
||||
|
||||
var tl = gsap.timeline({ paused: true, defaults: { ease: EASE } });
|
||||
|
||||
// Beat 1 — translate X, out and back twice.
|
||||
tl.to(word, { x: SLAM_X + "cqw", duration: slam }, cues[0])
|
||||
.to(word, { x: -SLAM_X + "cqw", duration: slam }, cues[0] + slam)
|
||||
.to(word, { x: SLAM_X + "cqw", duration: slam }, cues[0] + slam * 2)
|
||||
.to(word, { x: 0, duration: slam }, cues[0] + slam * 3);
|
||||
|
||||
// Beat 2 — translate Y, up first.
|
||||
tl.to(word, { y: -SLAM_Y + "cqh", duration: slam }, cues[1])
|
||||
.to(word, { y: SLAM_Y + "cqh", duration: slam }, cues[1] + slam)
|
||||
.to(word, { y: -SLAM_Y + "cqh", duration: slam }, cues[1] + slam * 2)
|
||||
.to(word, { y: 0, duration: slam }, cues[1] + slam * 3);
|
||||
|
||||
// Beat 3 — scale punch, up then down then up.
|
||||
tl.to(word, { scale: 4.04, duration: slam }, cues[2])
|
||||
.to(word, { scale: 0.466, duration: slam }, cues[2] + slam)
|
||||
.to(word, { scale: 4.04, duration: slam }, cues[2] + slam * 2)
|
||||
.to(word, { scale: 1, duration: slam }, cues[2] + slam * 3);
|
||||
|
||||
// Beats 4 to 6 — one full turn about each axis. A full turn ends where it
|
||||
// started, so each is a single tween rather than an out-and-back pair.
|
||||
tl.to(word, { rotationX: 360, duration: turn }, cues[3]);
|
||||
tl.to(word, { rotationY: 360, duration: turn }, cues[4]);
|
||||
tl.to(word, { rotation: 360, duration: turnZ }, cues[5]);
|
||||
|
||||
var beatsEnd = Math.max.apply(
|
||||
null,
|
||||
cues.map(function (cue, index) {
|
||||
return cue + LENGTHS[index];
|
||||
}),
|
||||
);
|
||||
var outStart = Math.max(beatsEnd, duration - out);
|
||||
|
||||
if (exit !== "none") {
|
||||
var leaving = { opacity: 0, duration: out, ease: "power2.in" };
|
||||
if (exit === "up") leaving.y = "-12cqh";
|
||||
tl.to(word, leaving, outStart);
|
||||
}
|
||||
|
||||
// Seeks past the last tween must still reach the blur's tracker, so the
|
||||
// timeline runs to the mount's full duration.
|
||||
tl.set(document.body, {}, duration);
|
||||
|
||||
// After every tween, before registration: the tracker tween the blur adds
|
||||
// needs the timeline's final duration.
|
||||
if (blurred) attachMotionBlur(word, tl, { fps: 30 });
|
||||
|
||||
tl.seek(0);
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["shutter-slam"] = tl;
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</template>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
{/* hf:generated-footer */}
|
||||
|
||||
Tagged `effect` `motion-blur` `shutter` `after-effects` `slam` `animation`.
|
||||
|
||||
## Related topics
|
||||
|
||||
- [Browse the complete Catalog](/catalog)
|
||||
- [Add assets and Catalog items in Studio](/studio/assets-and-blocks)
|
||||
- [Build a richer composition](/go-further)
|
||||
@@ -705,6 +705,7 @@
|
||||
"catalog/components/parallax-zoom",
|
||||
"catalog/components/rubber-band-bumper",
|
||||
"catalog/components/settings-toggle-flow",
|
||||
"catalog/components/shutter-slam",
|
||||
"catalog/components/signup-flow",
|
||||
"catalog/components/spotlight-card",
|
||||
"catalog/components/stagger-cascade",
|
||||
|
||||
@@ -3340,7 +3340,7 @@
|
||||
"name": "motion-blur",
|
||||
"type": "component",
|
||||
"title": "Motion Blur",
|
||||
"description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight SVG copies along the real trajectory",
|
||||
"description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight additive copies of the element along its real trajectory, so translation, scale, rotation, 3D rotation and skew all drive the smear",
|
||||
"tags": [
|
||||
"effect",
|
||||
"motion-blur",
|
||||
@@ -4215,6 +4215,22 @@
|
||||
"href": "/catalog/components/shimmer-sweep",
|
||||
"preview": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shimmer-sweep.png"
|
||||
},
|
||||
{
|
||||
"name": "shutter-slam",
|
||||
"type": "component",
|
||||
"title": "Shutter Slam",
|
||||
"description": "One word thrown through six single-property beats under integrated shutter blur — two translate slams, a scale punch, then a full turn about each axis — on the measured easing of the After Effects export the shutter model was fitted to",
|
||||
"tags": [
|
||||
"effect",
|
||||
"motion-blur",
|
||||
"shutter",
|
||||
"after-effects",
|
||||
"slam",
|
||||
"animation"
|
||||
],
|
||||
"href": "/catalog/components/shutter-slam",
|
||||
"preview": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shutter-slam.png"
|
||||
},
|
||||
{
|
||||
"name": "signup-flow",
|
||||
"type": "component",
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -15,25 +15,39 @@ const snippetHtml = readRepoFile("registry/components/motion-blur/motion-blur.ht
|
||||
|
||||
/** First line of the snippet's IIFE body, which runs to the `};` closing it at the same indent. */
|
||||
const BODY_FIRST_LINE = "if (!window._hfMbUid) window._hfMbUid = 0;";
|
||||
const SNIPPET_INDENT = " ".repeat(4);
|
||||
const INLINED_INDENT = " ".repeat(10);
|
||||
|
||||
/**
|
||||
* The snippet's IIFE body, leading whitespace dropped so the installable snippet and its inlined
|
||||
* copies compare regardless of how deeply each one nests it.
|
||||
*/
|
||||
function snippetBody(source: string, indent: string): string {
|
||||
const start = source.indexOf(indent + BODY_FIRST_LINE);
|
||||
const endMarker = `\n${indent}};`;
|
||||
const end = source.indexOf(endMarker, start);
|
||||
if (start < 0 || end < 0) {
|
||||
throw new Error(`could not locate the snippet body at indent ${indent.length}`);
|
||||
/** The snippet's IIFE body verbatim, located by the indent of its own first line, so a copy
|
||||
* nested in a component template is found as readily as one in a demo plate. */
|
||||
function snippetSource(source: string): string {
|
||||
const escaped = BODY_FIRST_LINE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const match = new RegExp(`^([ ]*)${escaped}$`, "m").exec(source);
|
||||
const indent = match?.[1];
|
||||
if (match === null || indent === undefined) {
|
||||
throw new Error("could not locate the snippet body");
|
||||
}
|
||||
return source
|
||||
.slice(start, end + endMarker.length)
|
||||
.split("\n")
|
||||
.map((line) => line.trimStart())
|
||||
.join("\n");
|
||||
const endMarker = `\n${indent}};`;
|
||||
const end = source.indexOf(endMarker, match.index);
|
||||
if (end < 0) throw new Error("could not locate the end of the snippet body");
|
||||
return source.slice(match.index, end + endMarker.length);
|
||||
}
|
||||
|
||||
/** Runs of code lines joined, because oxfmt wraps a statement differently at each nesting depth.
|
||||
* Comment lines stay on their own line, so prose drift is still caught. */
|
||||
function joinWrappedLines(body: string): string {
|
||||
const lines: string[] = [];
|
||||
for (const line of body.split("\n")) {
|
||||
const text = line.trim();
|
||||
if (text === "") continue;
|
||||
const previous = lines.at(-1);
|
||||
const separate = previous === undefined || text.startsWith("//") || previous.startsWith("//");
|
||||
if (separate) lines.push(text);
|
||||
else lines[lines.length - 1] = `${previous} ${text}`;
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function snippetBody(source: string): string {
|
||||
return joinWrappedLines(snippetSource(source));
|
||||
}
|
||||
|
||||
const FPS = 30;
|
||||
@@ -42,6 +56,8 @@ const FRAME_TIME_S = 5;
|
||||
const DURATION_S = 10;
|
||||
const WORD_WIDTH = 1046;
|
||||
const WORD_HEIGHT = 193;
|
||||
const PERSPECTIVE = "2000px";
|
||||
const COPIES = reference.subIntervalsPerWindow + 1;
|
||||
|
||||
/** The slice of GSAP's timeline API the snippet drives; `time()` reads, `time(value)` seeks. */
|
||||
interface Timeline {
|
||||
@@ -50,6 +66,9 @@ interface Timeline {
|
||||
to(target: unknown, vars: { onUpdate?: () => void }): Timeline;
|
||||
}
|
||||
|
||||
/** A resolved transform at one sample time, as `getComputedStyle` would report it. */
|
||||
type Trajectory = (framesFromNow: number) => string;
|
||||
|
||||
/**
|
||||
* The reference's own trajectory around the measured frame: a parabola through the core centres of
|
||||
* frames 4, 5 and 6, with frame 5 at t = 0. Offsets are relative to the frame-time position, so the
|
||||
@@ -62,6 +81,8 @@ function offsetAtFrames(df: number): number {
|
||||
return ((fwd + back) / 2) * df * df + ((fwd - back) / 2) * df;
|
||||
}
|
||||
|
||||
const translating: Trajectory = (df) => `matrix(1, 0, 0, 1, ${offsetAtFrames(df)}, 0)`;
|
||||
|
||||
function installSnippet(): void {
|
||||
const body = snippetHtml.slice(
|
||||
snippetHtml.indexOf("<script>") + "<script>".length,
|
||||
@@ -88,43 +109,92 @@ function makeTimeline(): { tl: Timeline; currentTime: () => number; fire: () =>
|
||||
return { tl, currentTime: () => now, fire: () => onUpdate?.() };
|
||||
}
|
||||
|
||||
function installGsap(currentTime: () => number, trajectory: (df: number) => number): void {
|
||||
(globalThis as unknown as { gsap: unknown }).gsap = {
|
||||
getProperty(_el: Element, prop: string) {
|
||||
if (prop === "x") return `${trajectory((currentTime() - FRAME_TIME_S) * FPS)}px`;
|
||||
if (prop === "scaleX" || prop === "scaleY") return 1;
|
||||
return 0;
|
||||
/**
|
||||
* happy-dom resolves no transforms of its own, so the element's computed style is the trajectory.
|
||||
* The stub also answers the declaration enumeration the style replay uses, and the perspective.
|
||||
*/
|
||||
function installComputedStyle(
|
||||
word: Element,
|
||||
currentTime: () => number,
|
||||
trajectory: Trajectory,
|
||||
opacity: () => string,
|
||||
perspective: () => string,
|
||||
): void {
|
||||
globalThis.getComputedStyle = ((element: Element) =>
|
||||
({
|
||||
length: 0,
|
||||
getPropertyValue: () => "",
|
||||
transform: element === word ? trajectory((currentTime() - FRAME_TIME_S) * FPS) : "none",
|
||||
transformOrigin: "50% 50%",
|
||||
opacity: element === word ? opacity() : "1",
|
||||
perspective: element === word ? "none" : perspective(),
|
||||
}) as unknown as CSSStyleDeclaration) as typeof globalThis.getComputedStyle;
|
||||
}
|
||||
|
||||
/** Captures the observers the snippet installs so a test can fire a resize itself. */
|
||||
function installResizeObserver(): { resize: () => void } {
|
||||
const callbacks: Array<() => void> = [];
|
||||
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = class {
|
||||
constructor(callback: () => void) {
|
||||
callbacks.push(callback);
|
||||
}
|
||||
observe(): void {}
|
||||
disconnect(): void {}
|
||||
};
|
||||
return {
|
||||
resize: () => {
|
||||
for (const callback of callbacks) callback();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface Attached {
|
||||
group: HTMLElement;
|
||||
word: HTMLElement;
|
||||
copies: HTMLElement[];
|
||||
fire: () => void;
|
||||
reattach: () => void;
|
||||
}
|
||||
|
||||
async function attach(
|
||||
options: Record<string, unknown>,
|
||||
trajectory: (df: number) => number = offsetAtFrames,
|
||||
): Promise<Element> {
|
||||
const el = document.createElement("div");
|
||||
el.id = "word";
|
||||
Object.defineProperty(el, "offsetWidth", { value: WORD_WIDTH });
|
||||
Object.defineProperty(el, "offsetHeight", { value: WORD_HEIGHT });
|
||||
document.body.appendChild(el);
|
||||
options: Record<string, unknown> = {},
|
||||
trajectory: Trajectory = translating,
|
||||
opacity: () => string = () => "1",
|
||||
perspective: () => string = () => PERSPECTIVE,
|
||||
): Promise<Attached> {
|
||||
const stage = document.createElement("div");
|
||||
document.body.appendChild(stage);
|
||||
const word = document.createElement("div");
|
||||
word.id = "word";
|
||||
Object.defineProperty(word, "offsetWidth", { value: WORD_WIDTH });
|
||||
Object.defineProperty(word, "offsetHeight", { value: WORD_HEIGHT });
|
||||
Object.defineProperty(word, "offsetLeft", { value: 437 });
|
||||
Object.defineProperty(word, "offsetTop", { value: 442 });
|
||||
stage.appendChild(word);
|
||||
|
||||
const { tl, currentTime, fire } = makeTimeline();
|
||||
installGsap(currentTime, trajectory);
|
||||
installComputedStyle(word, currentTime, trajectory, opacity, perspective);
|
||||
installSnippet();
|
||||
(
|
||||
const attachBlur = (
|
||||
window as unknown as { attachMotionBlur: (s: string, t: Timeline, o: unknown) => void }
|
||||
).attachMotionBlur("#word", tl, options);
|
||||
).attachMotionBlur;
|
||||
const reattach = () => attachBlur("#word", tl, { fps: FPS, ...options });
|
||||
reattach();
|
||||
|
||||
fire();
|
||||
await Promise.resolve();
|
||||
const filter = document.querySelector("filter");
|
||||
if (!filter) throw new Error("motion-blur filter was not created");
|
||||
return filter;
|
||||
const group = document.querySelector<HTMLElement>("[data-hf-motion-blur]");
|
||||
if (!group) throw new Error("motion-blur group was not created");
|
||||
return { group, word, copies: [...group.children] as HTMLElement[], fire, reattach };
|
||||
}
|
||||
|
||||
/** Horizontal offset of every duplicate, in window order. */
|
||||
function copyOffsets(filter: Element): number[] {
|
||||
return [...filter.querySelectorAll("feOffset")].map((node) => Number(node.getAttribute("dx")));
|
||||
/** Horizontal translation of every duplicate, in window order. */
|
||||
function copyOffsets(copies: HTMLElement[]): number[] {
|
||||
return copies.map((copy) => {
|
||||
const numbers = copy.style.transform.slice(copy.style.transform.lastIndexOf("(") + 1, -1);
|
||||
const parts = numbers.split(",").map((value) => Number.parseFloat(value));
|
||||
return parts[4] ?? Number.NaN;
|
||||
});
|
||||
}
|
||||
|
||||
/** The duplicates sitting at the two ends of the shutter window. */
|
||||
@@ -132,7 +202,7 @@ function windowEdges(offsets: number[]): { trailing: number; leading: number } {
|
||||
const [trailing] = offsets;
|
||||
const leading = offsets.at(-1);
|
||||
if (trailing === undefined || leading === undefined) {
|
||||
throw new Error("the filter carries no duplicates");
|
||||
throw new Error("the group carries no duplicates");
|
||||
}
|
||||
return { trailing, leading };
|
||||
}
|
||||
@@ -147,30 +217,34 @@ function copyPitches(offsets: number[]): number[] {
|
||||
return pitches;
|
||||
}
|
||||
|
||||
const originalGetComputedStyle = globalThis.getComputedStyle;
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
globalThis.getComputedStyle = originalGetComputedStyle;
|
||||
delete (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver;
|
||||
});
|
||||
|
||||
describe("motion-blur snippet copies", () => {
|
||||
// The demo and the example composition have to inline the snippet — a catalog demo is a single
|
||||
// self-contained file and cannot import one. That makes three copies of the same shutter model, so
|
||||
// The demos and the example composition have to inline the snippet — a catalog plate is a single
|
||||
// self-contained file and cannot import one. That makes four copies of the same shutter model, so
|
||||
// the copies are asserted equal here rather than left to drift silently.
|
||||
it.each([
|
||||
"registry/components/motion-blur/demo.html",
|
||||
"registry/components/shutter-slam/shutter-slam.html",
|
||||
"registry/components/shutter-slam/demo.html",
|
||||
"registry/examples/motion-blur/index.html",
|
||||
])("%s inlines the installable snippet verbatim", (relativePath) => {
|
||||
expect(snippetBody(readRepoFile(relativePath), INLINED_INDENT)).toBe(
|
||||
snippetBody(snippetHtml, SNIPPET_INDENT),
|
||||
);
|
||||
expect(snippetBody(readRepoFile(relativePath))).toBe(snippetBody(snippetHtml));
|
||||
});
|
||||
});
|
||||
|
||||
describe("motion-blur shutter matches the After Effects reference", () => {
|
||||
it("opens the shutter over the frame before and the frame after, at the measured sub-interval count", async () => {
|
||||
const offsets = copyOffsets(await attach({ fps: FPS }));
|
||||
const { trailing, leading } = windowEdges(offsets);
|
||||
const { copies } = await attach();
|
||||
const { trailing, leading } = windowEdges(copyOffsets(copies));
|
||||
|
||||
expect(offsets).toHaveLength(reference.subIntervalsPerWindow + 1);
|
||||
expect(copies).toHaveLength(COPIES);
|
||||
expect(trailing).toBeCloseTo(-reference.trailingDisplacementPx, 1);
|
||||
expect(leading).toBeCloseTo(reference.leadingDisplacementPx, 1);
|
||||
});
|
||||
@@ -179,69 +253,131 @@ describe("motion-blur shutter matches the After Effects reference", () => {
|
||||
// The reference's staircase is even (15, 16, 16, 15, 16, 16, 16 px across a 125.8 px frame
|
||||
// displacement), so a constant-velocity trajectory has to come out evenly spaced at 1/8 frame.
|
||||
const speed = reference.trailingDisplacementPx;
|
||||
const offsets = copyOffsets(await attach({ fps: FPS }, (df) => speed * df));
|
||||
const { copies } = await attach({}, (df) => `matrix(1, 0, 0, 1, ${speed * df}, 0)`);
|
||||
const expected = speed / (reference.subIntervalsPerWindow / 2);
|
||||
|
||||
for (const pitch of copyPitches(offsets)) expect(pitch).toBeCloseTo(expected, 3);
|
||||
for (const pitch of copyPitches(copyOffsets(copies))) expect(pitch).toBeCloseTo(expected, 3);
|
||||
});
|
||||
|
||||
it("gives every duplicate the measured 1/16 opacity and none full opacity", async () => {
|
||||
const filter = await attach({ fps: FPS });
|
||||
const weights = [...filter.querySelectorAll("feComposite[operator='arithmetic']")].map((node) =>
|
||||
Number(node.getAttribute("k3")),
|
||||
);
|
||||
const { copies } = await attach();
|
||||
|
||||
expect(weights).toHaveLength(reference.subIntervalsPerWindow);
|
||||
for (const weight of weights) expect(weight).toBeCloseTo(reference.copyOpacity, 6);
|
||||
expect(copies).toHaveLength(COPIES);
|
||||
for (const copy of copies) {
|
||||
expect(Number(copy.style.opacity)).toBeCloseTo(reference.copyOpacity, 6);
|
||||
expect(copy.style.mixBlendMode).toBe("plus-lighter");
|
||||
}
|
||||
// Flat, not tapered: the reference's plateau increments are all the same height.
|
||||
expect(new Set(weights).size).toBe(1);
|
||||
expect(new Set(copies.map((copy) => copy.style.opacity)).size).toBe(1);
|
||||
});
|
||||
|
||||
it("accumulates every duplicate exactly once, in one unbroken chain", async () => {
|
||||
const filter = await attach({ fps: FPS });
|
||||
const adds = [...filter.querySelectorAll("feComposite[operator='arithmetic']")];
|
||||
const weight = 1 / reference.subIntervalsPerWindow;
|
||||
it("adds the duplicates among themselves, not onto the page", async () => {
|
||||
// plus-lighter adds premultiplied colour, so without a backdrop of its own the first
|
||||
// duplicate would add onto whatever is behind the element and blow a light page out to
|
||||
// white. The isolation is the only thing standing between the shutter sum and the page.
|
||||
const { group } = await attach();
|
||||
|
||||
// The first composite is the only one that has to scale BOTH inputs, because it is the
|
||||
// only one whose `in` is a raw duplicate rather than the running sum. Getting its k2
|
||||
// wrong lets one duplicate through at full weight — the exact thing the reference rules out.
|
||||
expect(adds[0]?.getAttribute("in")).toBe("s0");
|
||||
expect(Number(adds[0]?.getAttribute("k2"))).toBeCloseTo(weight, 6);
|
||||
for (const add of adds.slice(1)) expect(Number(add.getAttribute("k2"))).toBe(1);
|
||||
|
||||
// Each composite must fold in the next duplicate and feed the one after it, so every
|
||||
// duplicate reaches the output and none is added twice.
|
||||
adds.forEach((add, index) => {
|
||||
expect(add.getAttribute("in")).toBe(index === 0 ? "s0" : `a${index}`);
|
||||
expect(add.getAttribute("in2")).toBe(`s${index + 1}`);
|
||||
expect(add.getAttribute("result")).toBe(`a${index + 1}`);
|
||||
});
|
||||
expect(group.style.isolation).toBe("isolate");
|
||||
});
|
||||
|
||||
it("composites the sharp frame-time instance over the full accumulated smear", async () => {
|
||||
const filter = await attach({ fps: FPS });
|
||||
const last = filter.lastElementChild;
|
||||
it("paints the sharp frame-time instance over the accumulated smear", async () => {
|
||||
const { group, word } = await attach();
|
||||
|
||||
expect(last?.tagName).toBe("feComposite");
|
||||
expect(last?.getAttribute("operator")).toBe("over");
|
||||
expect(last?.getAttribute("in")).toBe("SourceGraphic");
|
||||
// in2 must be the END of the accumulation chain, not some intermediate or single copy.
|
||||
expect(last?.getAttribute("in2")).toBe(`a${reference.subIntervalsPerWindow}`);
|
||||
expect(last?.getAttribute("result")).toBeNull();
|
||||
// Document order is the paint order for positioned siblings at the same z-index, so the
|
||||
// group has to precede the element rather than follow it.
|
||||
expect(group.nextElementSibling).toBe(word);
|
||||
expect(word.style.opacity).toBe("");
|
||||
});
|
||||
|
||||
it("keeps the sharp instance inside the filter region when the window is entirely one-sided", async () => {
|
||||
// shutterPhase 0 opens the shutter at the frame time, so every duplicate is ahead of the
|
||||
// element and no duplicate sits at offset 0 — but the sharp instance still does. A region
|
||||
// derived from the duplicates alone starts inside the element's own box and clips it.
|
||||
const filter = await attach({ fps: FPS, shutterPhase: 360 });
|
||||
const offsets = copyOffsets(filter);
|
||||
it("carries the element's own opacity on the smear", async () => {
|
||||
// A beat that moves and fades at once must not leave a full-strength smear behind a
|
||||
// vanishing element. The weight stays on the duplicates; the fade rides the group.
|
||||
const { group, copies } = await attach({}, translating, () => "0.25");
|
||||
|
||||
expect(Math.min(...offsets)).toBeGreaterThan(0);
|
||||
expect(Number.parseFloat(filter.getAttribute("x") ?? "")).toBeLessThanOrEqual(0);
|
||||
const right =
|
||||
Number.parseFloat(filter.getAttribute("x") ?? "") +
|
||||
Number.parseFloat(filter.getAttribute("width") ?? "");
|
||||
expect(right).toBeGreaterThanOrEqual((Math.max(...offsets) / WORD_WIDTH) * 100 + 100);
|
||||
expect(group.style.opacity).toBe("0.25");
|
||||
for (const copy of copies)
|
||||
expect(Number(copy.style.opacity)).toBeCloseTo(reference.copyOpacity, 6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("motion-blur drivers", () => {
|
||||
// The output stage carries each duplicate's whole resolved transform, so any property that
|
||||
// reaches `transform` smears. The previous stage offset one rasterisation, which meant a beat
|
||||
// that only scaled or only rotated sampled a displacement of zero and rendered sharp.
|
||||
it("smears a scale beat that never translates", async () => {
|
||||
const { copies } = await attach(
|
||||
{},
|
||||
(df) => `matrix(${1 + df * 0.5}, 0, 0, ${1 + df * 0.5}, 0, 0)`,
|
||||
);
|
||||
const scales = copies.map((copy) => copy.style.transform);
|
||||
|
||||
expect(new Set(scales).size).toBe(COPIES);
|
||||
expect(copies[0]?.style.transform).toContain("matrix(0.5");
|
||||
});
|
||||
|
||||
it("smears a 3D rotation beat and gives every duplicate its own perspective", async () => {
|
||||
// mix-blend-mode flattens preserve-3d, so a duplicate cannot inherit the parent's 3D
|
||||
// context: each one carries the parent's perspective as its own first transform function.
|
||||
const { copies } = await attach(
|
||||
{},
|
||||
(df) =>
|
||||
`matrix3d(${Math.cos(df)}, 0, ${Math.sin(df)}, 0, 0, 1, 0, 0, ${-Math.sin(df)}, 0, ${Math.cos(df)}, 0, 0, 0, 0, 1)`,
|
||||
);
|
||||
|
||||
expect(new Set(copies.map((copy) => copy.style.transform)).size).toBe(COPIES);
|
||||
for (const copy of copies) {
|
||||
expect(copy.style.transform.startsWith(`perspective(${PERSPECTIVE})`)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("renders sharp when nothing the transform can express has changed", async () => {
|
||||
// The deadband is what keeps a held frame from paying for 17 duplicates of a still element.
|
||||
const { group } = await attach({}, () => "matrix(1, 0, 0, 1, 0, 0)");
|
||||
|
||||
expect(group.style.display).toBe("none");
|
||||
});
|
||||
|
||||
it("renders sharp below half a pixel of travel", async () => {
|
||||
const { group } = await attach({}, (df) => `matrix(1, 0, 0, 1, ${df * 0.1}, 0)`);
|
||||
|
||||
expect(group.style.display).toBe("none");
|
||||
});
|
||||
|
||||
it("blurs a target once, however many times it is named", async () => {
|
||||
// A second set of copies over the first would double the ink at every sample, so
|
||||
// the second call has to leave the element alone rather than stack onto it.
|
||||
const { reattach } = await attach();
|
||||
reattach();
|
||||
|
||||
expect(document.querySelectorAll("[data-hf-motion-blur]")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("re-reads the copies' styles when the element's box changes", async () => {
|
||||
// Container-relative styles (a cqw font size, a cqw perspective) are px by the time
|
||||
// they are read, so a preview that resizes after attaching would otherwise keep the
|
||||
// smear at the old size for the rest of the render.
|
||||
const observer = installResizeObserver();
|
||||
let perspective = PERSPECTIVE;
|
||||
const { copies, fire } = await attach(
|
||||
{},
|
||||
translating,
|
||||
() => "1",
|
||||
() => perspective,
|
||||
);
|
||||
expect(copies[0]?.style.transform.startsWith(`perspective(${PERSPECTIVE})`)).toBe(true);
|
||||
|
||||
perspective = "900px";
|
||||
observer.resize();
|
||||
fire();
|
||||
await Promise.resolve();
|
||||
|
||||
for (const copy of copies)
|
||||
expect(copy.style.transform.startsWith("perspective(900px)")).toBe(true);
|
||||
});
|
||||
|
||||
it("disables the smear entirely at shutterAngle 0", async () => {
|
||||
const { group } = await attach({ shutterAngle: 0 });
|
||||
|
||||
expect(group.style.display).toBe("none");
|
||||
});
|
||||
});
|
||||
|
||||
Binary file not shown.
@@ -2,7 +2,7 @@
|
||||
"model": "bge-small-en-v1.5",
|
||||
"modelRevision": "ea104dacec62c0de699686887e3f920caeb4f3e3",
|
||||
"dimensions": 384,
|
||||
"revision": "34370735fa1a93099519873178e547c43b14f3bd69491013577515f4bb4f5957",
|
||||
"revision": "e1c1f6eb5505d4b68d8240850425465c8375fed95b0d30b31328a5a754ae7f24",
|
||||
"names": [
|
||||
"ai-chat-reveal",
|
||||
"animated-bar-chart",
|
||||
@@ -289,6 +289,7 @@
|
||||
"shared-axis-z",
|
||||
"sheet-spring-up",
|
||||
"shimmer-sweep",
|
||||
"shutter-slam",
|
||||
"signup-flow",
|
||||
"simulated-cursor",
|
||||
"skeleton-reveal",
|
||||
|
||||
+173
-155
@@ -259,6 +259,7 @@
|
||||
<script>
|
||||
(function () {
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
@@ -277,9 +278,55 @@
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// objectBoundingBox percentage for a px offset plus padding.
|
||||
function regionPercent(offset, size, padPercent) {
|
||||
return ((offset / size) * 100 + padPercent).toFixed(2) + "%";
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
@@ -290,49 +337,7 @@
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var axis = opts.axis || "both";
|
||||
var fps = resolveFps(opts.fps);
|
||||
var useX = axis !== "y";
|
||||
var useY = axis !== "x";
|
||||
|
||||
// Untransformed box size; SVG elements have no offsetWidth, so use the
|
||||
// same bbox GSAP uses to resolve their percent transforms.
|
||||
function boxSize(el, horizontal) {
|
||||
var box = typeof el.offsetWidth === "number" ? el : el.getBBox ? el.getBBox() : null;
|
||||
var size = box
|
||||
? horizontal
|
||||
? box.offsetWidth || box.width
|
||||
: box.offsetHeight || box.height
|
||||
: 0;
|
||||
return size || el.getBoundingClientRect()[horizontal ? "width" : "height"] || 1;
|
||||
}
|
||||
|
||||
// GSAP x/y may carry a % unit and xPercent/yPercent is a separate term;
|
||||
// resolve both against the element's own box so samples are in px.
|
||||
function readAxis(el, prop, percentProp, size) {
|
||||
var px = parseFloat(gsap.getProperty(el, prop, "px")) || 0;
|
||||
var percent = parseFloat(gsap.getProperty(el, percentProp)) || 0;
|
||||
return px + (percent * size) / 100;
|
||||
}
|
||||
|
||||
function readPosition(el) {
|
||||
return {
|
||||
x: useX ? readAxis(el, "x", "xPercent", boxSize(el, true)) : 0,
|
||||
y: useY ? readAxis(el, "y", "yPercent", boxSize(el, false)) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// CSS filters run in the element's pre-transform space while GSAP x/y are
|
||||
// post-transform, so a displacement is mapped through the inverse of the
|
||||
// element's own scale/rotation. Ancestor transforms are not compensated.
|
||||
function toFilterSpace(el, dx, dy) {
|
||||
var sx = parseFloat(gsap.getProperty(el, "scaleX")) || 1;
|
||||
var sy = parseFloat(gsap.getProperty(el, "scaleY")) || 1;
|
||||
var theta = ((parseFloat(gsap.getProperty(el, "rotation")) || 0) * Math.PI) / 180;
|
||||
var cos = Math.cos(theta);
|
||||
var sin = Math.sin(theta);
|
||||
return { dx: (dx * cos + dy * sin) / sx, dy: (-dx * sin + dy * cos) / sy };
|
||||
}
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
@@ -346,83 +351,103 @@
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
var ns = "http://www.w3.org/2000/svg";
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var weight = String(1 / samples);
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// One SVG filter per target: N+1 offset copies of SourceGraphic added at 1/N
|
||||
// each, then the element itself over the top. Accumulating in sRGB matches
|
||||
// AE's default (non-linear) 8-bpc working space.
|
||||
var state = targets.map(function (el) {
|
||||
var uid = "hf-mb-" + window._hfMbUid++;
|
||||
var svg = document.createElementNS(ns, "svg");
|
||||
svg.setAttribute("style", "position:absolute;width:0;height:0;overflow:hidden;");
|
||||
|
||||
var filter = document.createElementNS(ns, "filter");
|
||||
filter.id = uid;
|
||||
filter.setAttribute("color-interpolation-filters", "sRGB");
|
||||
|
||||
var offsets = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var feOff = document.createElementNS(ns, "feOffset");
|
||||
feOff.setAttribute("in", "SourceGraphic");
|
||||
feOff.setAttribute("dx", "0");
|
||||
feOff.setAttribute("dy", "0");
|
||||
feOff.setAttribute("result", "s" + k);
|
||||
filter.appendChild(feOff);
|
||||
offsets.push(feOff);
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
|
||||
// Pairwise accumulation: the first composite scales both inputs by 1/N, every
|
||||
// later one adds the next copy at 1/N to the running sum. The N+1 weights total
|
||||
// (N+1)/N, so an element wider than its own smear saturates through the middle
|
||||
// and the filter clamps there. That is the saturation the reference shows, and
|
||||
// the sharp instance covers the same region regardless.
|
||||
var accumulated = "s0";
|
||||
for (var c = 1; c < copies; c++) {
|
||||
var feComp = document.createElementNS(ns, "feComposite");
|
||||
feComp.setAttribute("operator", "arithmetic");
|
||||
feComp.setAttribute("in", accumulated);
|
||||
feComp.setAttribute("in2", "s" + c);
|
||||
feComp.setAttribute("k1", "0");
|
||||
feComp.setAttribute("k2", c === 1 ? weight : "1");
|
||||
feComp.setAttribute("k3", weight);
|
||||
feComp.setAttribute("k4", "0");
|
||||
accumulated = "a" + c;
|
||||
feComp.setAttribute("result", accumulated);
|
||||
filter.appendChild(feComp);
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
|
||||
// The frame-time instance is drawn sharp, at full opacity, over the smear.
|
||||
// Every blurred copy stays at 1/N, so nothing but the instance the frame is
|
||||
// actually at reads as solid. Unnamed, so it is the filter output.
|
||||
var feOver = document.createElementNS(ns, "feComposite");
|
||||
feOver.setAttribute("operator", "over");
|
||||
feOver.setAttribute("in", "SourceGraphic");
|
||||
feOver.setAttribute("in2", accumulated);
|
||||
filter.appendChild(feOver);
|
||||
|
||||
svg.appendChild(filter);
|
||||
document.body.appendChild(svg);
|
||||
|
||||
return { el: el, offsets: offsets, filter: filter, filterId: uid, xs: [], ys: [] };
|
||||
});
|
||||
|
||||
// The element may carry its own inline filter (authored or tweened by
|
||||
// GSAP); the blur is appended to that chain and removed from it, never
|
||||
// written over it.
|
||||
var OWN_FILTER = /\s*url\(["']?#hf-mb-\d+["']?\)/g;
|
||||
|
||||
function baseFilter(el) {
|
||||
return el.style.filter.replace(OWN_FILTER, "").trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
function clearBlur(s) {
|
||||
s.el.style.filter = baseFilter(s.el);
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function") new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
@@ -430,7 +455,9 @@
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(clearBlur);
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -440,15 +467,13 @@
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read positions, then restore the frame time.
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
var pos = readPosition(s.el);
|
||||
s.xs[k] = pos.x;
|
||||
s.ys[k] = pos.y;
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
@@ -456,48 +481,42 @@
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readPosition(s.el);
|
||||
var minDx = Infinity;
|
||||
var maxDx = -Infinity;
|
||||
var minDy = Infinity;
|
||||
var maxDy = -Infinity;
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
var d = toFilterSpace(s.el, s.xs[i] - current.x, s.ys[i] - current.y);
|
||||
var dx = d.dx;
|
||||
var dy = d.dy;
|
||||
s.offsets[i].setAttribute("dx", dx.toFixed(3));
|
||||
s.offsets[i].setAttribute("dy", dy.toFixed(3));
|
||||
if (dx < minDx) minDx = dx;
|
||||
if (dx > maxDx) maxDx = dx;
|
||||
if (dy < minDy) minDy = dy;
|
||||
if (dy > maxDy) maxDy = dy;
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Below half a pixel of smear the average is indistinguishable from
|
||||
// the source — render sharp instead of paying for the filter.
|
||||
if (maxDx - minDx < 0.5 && maxDy - minDy < 0.5) {
|
||||
clearBlur(s);
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// Grow the filter region to cover every copy AND the sharp instance the
|
||||
// final composite draws at offset 0 (objectBoundingBox units, 10% padding
|
||||
// so anti-aliased edges are not clipped). Clamping the bounds through 0
|
||||
// matters whenever the window sits entirely on one side of the frame time
|
||||
// — any shutterPhase above 0 or below -shutterAngle — because then no copy
|
||||
// is at 0 and a region derived from the copies alone cuts the instance off.
|
||||
var x0 = Math.min(0, minDx);
|
||||
var x1 = Math.max(0, maxDx);
|
||||
var y0 = Math.min(0, minDy);
|
||||
var y1 = Math.max(0, maxDy);
|
||||
var w = boxSize(s.el, true);
|
||||
var h = boxSize(s.el, false);
|
||||
s.filter.setAttribute("x", regionPercent(x0, w, -10));
|
||||
s.filter.setAttribute("width", regionPercent(x1 - x0, w, 120));
|
||||
s.filter.setAttribute("y", regionPercent(y0, h, -10));
|
||||
s.filter.setAttribute("height", regionPercent(y1 - y0, h, 120));
|
||||
var base = baseFilter(s.el);
|
||||
s.el.style.filter = (base ? base + " " : "") + "url(#" + s.filterId + ")";
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
@@ -542,7 +561,6 @@
|
||||
attachMotionBlur(
|
||||
["#s1", "#s2", "#s3", "#s4", "#s5", "#t1", "#t2", "#t3", "#t4", "#t5"],
|
||||
tl,
|
||||
{ axis: "x" },
|
||||
);
|
||||
|
||||
window.__timelines = window.__timelines || {};
|
||||
|
||||
+215
-174
@@ -10,22 +10,31 @@
|
||||
|
||||
1. After every timeline update (each rendered frame), the snippet seeks
|
||||
the timeline to `samplesPerFrame` sub-frame times spread evenly across
|
||||
the shutter window, reads each target's GSAP x/y at every sample, then
|
||||
restores the frame time. Seeks run with events suppressed, so no user
|
||||
callbacks fire and the DOM ends up exactly where the frame left it.
|
||||
2. An SVG filter stacks one copy of the element per sample (feOffset to
|
||||
the sampled position relative to the current one) and adds them at
|
||||
equal weight (feComposite arithmetic, 1/N each, sRGB space). Result:
|
||||
a box smear along the actual trajectory whose length is speed ×
|
||||
shutter time, with no decaying one-sided trail. The tails — where
|
||||
fewer copies overlap — step down evenly at 1/N per copy; wherever the
|
||||
element travels less than its own size the copies pile up past 1 and
|
||||
clamp, so the middle of the smear is solid rather than a plateau.
|
||||
3. The element itself is then composited over that smear, sharp and at
|
||||
full opacity. No single duplicate ever exceeds 1/N, so a moving edge
|
||||
resolves as a staircase of ghosts behind a solid frame-time instance.
|
||||
4. When the sampled positions collapse to the current one (element at
|
||||
rest), the filter is removed so the element renders sharp.
|
||||
the shutter window, reads each target's RESOLVED `transform` at every
|
||||
sample, then restores the frame time. Seeks run with events suppressed,
|
||||
so no user callbacks fire and the DOM ends up exactly where the frame
|
||||
left it. Reading the resolved matrix rather than a list of named GSAP
|
||||
properties is what makes every driver work: translation, scale,
|
||||
rotation, 3D rotation and skew arrive in the same one value, and a
|
||||
driver nobody thought of needs no change here.
|
||||
2. One copy of the element per sample is stacked in an isolated group,
|
||||
each carrying its sample's transform, each at 1/N opacity with
|
||||
`mix-blend-mode: plus-lighter`. plus-lighter adds premultiplied colour,
|
||||
so N+1 copies at 1/N sum to the average — the shutter integral. The
|
||||
isolation is load-bearing: without a transparent backdrop of its own
|
||||
the first copy would add onto the page and blow a light background out
|
||||
to white. Result: a smear along the actual trajectory whose extent is
|
||||
speed × shutter time, with no decaying one-sided trail. The tails —
|
||||
where fewer copies overlap — step down evenly at 1/N per copy; wherever
|
||||
the element travels less than its own size the copies pile up past 1
|
||||
and clamp, so the middle of the smear is solid rather than a plateau.
|
||||
3. The element itself paints over that group, sharp and at full opacity.
|
||||
No single copy ever exceeds 1/N, so a moving edge resolves as a
|
||||
staircase of ghosts behind a solid frame-time instance. The group
|
||||
carries the element's own opacity, so a beat that moves and fades at
|
||||
once fades its smear with it.
|
||||
4. When every sampled transform collapses to the current one (element at
|
||||
rest), the group is hidden so the element renders sharp.
|
||||
|
||||
Shutter window (AE semantics, per frame at time t, frame interval 1/fps):
|
||||
shutterTime = shutterAngle / 360 / fps
|
||||
@@ -46,9 +55,23 @@
|
||||
instance on top is what keeps total ink above the unblurred frame's.
|
||||
|
||||
Requirements:
|
||||
- Elements must be animated via GSAP x/y (transform), not left/top. The
|
||||
element's own scale/rotation is compensated; skew, 3D rotation and
|
||||
transformed ancestors are not.
|
||||
- Elements must be animated via `transform` (GSAP x/y/scale/rotation and the
|
||||
3D and skew properties all qualify), not left/top. Transformed ancestors
|
||||
are still not compensated.
|
||||
- A 3D beat reads its perspective off the element's parent and applies it per
|
||||
copy, so the vanishing point follows each copy's transform-origin rather
|
||||
than the parent's perspective-origin. Those agree when the element is
|
||||
centred in its perspective parent, which is how a 3D beat is authored.
|
||||
- A copy drops the element's id but keeps its classes, because a class rule is
|
||||
the only thing that can still style a copy's pseudo-elements. So a selector
|
||||
written against a class matches the copies too: after attaching, address the
|
||||
element by id or by reference, never by a class a copy also carries.
|
||||
- A target is blurred once: a second attachMotionBlur() call naming the same
|
||||
element leaves the first call's copies in place rather than stacking a
|
||||
second set over them.
|
||||
- Cost is N + 1 copies of the target's whole subtree, restyled on attach and
|
||||
on resize and re-transformed every frame. Point it at the element that
|
||||
moves, not at a container holding it.
|
||||
- The host must render the timeline for the blur to update — HyperFrames
|
||||
seeks every frame. A fresh paused timeline that is never seeked shows no
|
||||
blur on its first frame.
|
||||
@@ -71,12 +94,12 @@
|
||||
fps — composition frame rate (default: the root's data-fps,
|
||||
else 30). Pass it explicitly when rendering with an
|
||||
fps override (`hyperframes render --fps`).
|
||||
axis — "x" | "y" | "both" (default "both")
|
||||
-->
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
@@ -95,9 +118,55 @@
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// objectBoundingBox percentage for a px offset plus padding.
|
||||
function regionPercent(offset, size, padPercent) {
|
||||
return ((offset / size) * 100 + padPercent).toFixed(2) + "%";
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
@@ -108,49 +177,7 @@
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var axis = opts.axis || "both";
|
||||
var fps = resolveFps(opts.fps);
|
||||
var useX = axis !== "y";
|
||||
var useY = axis !== "x";
|
||||
|
||||
// Untransformed box size; SVG elements have no offsetWidth, so use the
|
||||
// same bbox GSAP uses to resolve their percent transforms.
|
||||
function boxSize(el, horizontal) {
|
||||
var box = typeof el.offsetWidth === "number" ? el : el.getBBox ? el.getBBox() : null;
|
||||
var size = box
|
||||
? horizontal
|
||||
? box.offsetWidth || box.width
|
||||
: box.offsetHeight || box.height
|
||||
: 0;
|
||||
return size || el.getBoundingClientRect()[horizontal ? "width" : "height"] || 1;
|
||||
}
|
||||
|
||||
// GSAP x/y may carry a % unit and xPercent/yPercent is a separate term;
|
||||
// resolve both against the element's own box so samples are in px.
|
||||
function readAxis(el, prop, percentProp, size) {
|
||||
var px = parseFloat(gsap.getProperty(el, prop, "px")) || 0;
|
||||
var percent = parseFloat(gsap.getProperty(el, percentProp)) || 0;
|
||||
return px + (percent * size) / 100;
|
||||
}
|
||||
|
||||
function readPosition(el) {
|
||||
return {
|
||||
x: useX ? readAxis(el, "x", "xPercent", boxSize(el, true)) : 0,
|
||||
y: useY ? readAxis(el, "y", "yPercent", boxSize(el, false)) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// CSS filters run in the element's pre-transform space while GSAP x/y are
|
||||
// post-transform, so a displacement is mapped through the inverse of the
|
||||
// element's own scale/rotation. Ancestor transforms are not compensated.
|
||||
function toFilterSpace(el, dx, dy) {
|
||||
var sx = parseFloat(gsap.getProperty(el, "scaleX")) || 1;
|
||||
var sy = parseFloat(gsap.getProperty(el, "scaleY")) || 1;
|
||||
var theta = ((parseFloat(gsap.getProperty(el, "rotation")) || 0) * Math.PI) / 180;
|
||||
var cos = Math.cos(theta);
|
||||
var sin = Math.sin(theta);
|
||||
return { dx: (dx * cos + dy * sin) / sx, dy: (-dx * sin + dy * cos) / sy };
|
||||
}
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
@@ -164,83 +191,103 @@
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
var ns = "http://www.w3.org/2000/svg";
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var weight = String(1 / samples);
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// One SVG filter per target: N+1 offset copies of SourceGraphic added at 1/N
|
||||
// each, then the element itself over the top. Accumulating in sRGB matches
|
||||
// AE's default (non-linear) 8-bpc working space.
|
||||
var state = targets.map(function (el) {
|
||||
var uid = "hf-mb-" + window._hfMbUid++;
|
||||
var svg = document.createElementNS(ns, "svg");
|
||||
svg.setAttribute("style", "position:absolute;width:0;height:0;overflow:hidden;");
|
||||
|
||||
var filter = document.createElementNS(ns, "filter");
|
||||
filter.id = uid;
|
||||
filter.setAttribute("color-interpolation-filters", "sRGB");
|
||||
|
||||
var offsets = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var feOff = document.createElementNS(ns, "feOffset");
|
||||
feOff.setAttribute("in", "SourceGraphic");
|
||||
feOff.setAttribute("dx", "0");
|
||||
feOff.setAttribute("dy", "0");
|
||||
feOff.setAttribute("result", "s" + k);
|
||||
filter.appendChild(feOff);
|
||||
offsets.push(feOff);
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
|
||||
// Pairwise accumulation: the first composite scales both inputs by 1/N, every
|
||||
// later one adds the next copy at 1/N to the running sum. The N+1 weights total
|
||||
// (N+1)/N, so an element wider than its own smear saturates through the middle
|
||||
// and the filter clamps there. That is the saturation the reference shows, and
|
||||
// the sharp instance covers the same region regardless.
|
||||
var accumulated = "s0";
|
||||
for (var c = 1; c < copies; c++) {
|
||||
var feComp = document.createElementNS(ns, "feComposite");
|
||||
feComp.setAttribute("operator", "arithmetic");
|
||||
feComp.setAttribute("in", accumulated);
|
||||
feComp.setAttribute("in2", "s" + c);
|
||||
feComp.setAttribute("k1", "0");
|
||||
feComp.setAttribute("k2", c === 1 ? weight : "1");
|
||||
feComp.setAttribute("k3", weight);
|
||||
feComp.setAttribute("k4", "0");
|
||||
accumulated = "a" + c;
|
||||
feComp.setAttribute("result", accumulated);
|
||||
filter.appendChild(feComp);
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
|
||||
// The frame-time instance is drawn sharp, at full opacity, over the smear.
|
||||
// Every blurred copy stays at 1/N, so nothing but the instance the frame is
|
||||
// actually at reads as solid. Unnamed, so it is the filter output.
|
||||
var feOver = document.createElementNS(ns, "feComposite");
|
||||
feOver.setAttribute("operator", "over");
|
||||
feOver.setAttribute("in", "SourceGraphic");
|
||||
feOver.setAttribute("in2", accumulated);
|
||||
filter.appendChild(feOver);
|
||||
|
||||
svg.appendChild(filter);
|
||||
document.body.appendChild(svg);
|
||||
|
||||
return { el: el, offsets: offsets, filter: filter, filterId: uid, xs: [], ys: [] };
|
||||
});
|
||||
|
||||
// The element may carry its own inline filter (authored or tweened by
|
||||
// GSAP); the blur is appended to that chain and removed from it, never
|
||||
// written over it.
|
||||
var OWN_FILTER = /\s*url\(["']?#hf-mb-\d+["']?\)/g;
|
||||
|
||||
function baseFilter(el) {
|
||||
return el.style.filter.replace(OWN_FILTER, "").trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
function clearBlur(s) {
|
||||
s.el.style.filter = baseFilter(s.el);
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function") new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
@@ -248,7 +295,9 @@
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(clearBlur);
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -258,15 +307,13 @@
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read positions, then restore the frame time.
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
var pos = readPosition(s.el);
|
||||
s.xs[k] = pos.x;
|
||||
s.ys[k] = pos.y;
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
@@ -274,48 +321,42 @@
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readPosition(s.el);
|
||||
var minDx = Infinity;
|
||||
var maxDx = -Infinity;
|
||||
var minDy = Infinity;
|
||||
var maxDy = -Infinity;
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
var d = toFilterSpace(s.el, s.xs[i] - current.x, s.ys[i] - current.y);
|
||||
var dx = d.dx;
|
||||
var dy = d.dy;
|
||||
s.offsets[i].setAttribute("dx", dx.toFixed(3));
|
||||
s.offsets[i].setAttribute("dy", dy.toFixed(3));
|
||||
if (dx < minDx) minDx = dx;
|
||||
if (dx > maxDx) maxDx = dx;
|
||||
if (dy < minDy) minDy = dy;
|
||||
if (dy > maxDy) maxDy = dy;
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Below half a pixel of smear the average is indistinguishable from
|
||||
// the source — render sharp instead of paying for the filter.
|
||||
if (maxDx - minDx < 0.5 && maxDy - minDy < 0.5) {
|
||||
clearBlur(s);
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// Grow the filter region to cover every copy AND the sharp instance the
|
||||
// final composite draws at offset 0 (objectBoundingBox units, 10% padding
|
||||
// so anti-aliased edges are not clipped). Clamping the bounds through 0
|
||||
// matters whenever the window sits entirely on one side of the frame time
|
||||
// — any shutterPhase above 0 or below -shutterAngle — because then no copy
|
||||
// is at 0 and a region derived from the copies alone cuts the instance off.
|
||||
var x0 = Math.min(0, minDx);
|
||||
var x1 = Math.max(0, maxDx);
|
||||
var y0 = Math.min(0, minDy);
|
||||
var y1 = Math.max(0, maxDy);
|
||||
var w = boxSize(s.el, true);
|
||||
var h = boxSize(s.el, false);
|
||||
s.filter.setAttribute("x", regionPercent(x0, w, -10));
|
||||
s.filter.setAttribute("width", regionPercent(x1 - x0, w, 120));
|
||||
s.filter.setAttribute("y", regionPercent(y0, h, -10));
|
||||
s.filter.setAttribute("height", regionPercent(y1 - y0, h, 120));
|
||||
var base = baseFilter(s.el);
|
||||
s.el.style.filter = (base ? base + " " : "") + "url(#" + s.filterId + ")";
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"name": "motion-blur",
|
||||
"type": "hyperframes:component",
|
||||
"title": "Motion Blur",
|
||||
"description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight SVG copies along the real trajectory",
|
||||
"description": "After Effects-style motion blur — integrates each element over a shutter window (shutter angle, phase, samples per frame) by sampling the GSAP timeline at sub-frame times and averaging equal-weight additive copies of the element along its real trajectory, so translation, scale, rotation, 3D rotation and skew all drive the smear",
|
||||
"tags": ["effect", "motion-blur", "shutter", "after-effects", "velocity", "animation"],
|
||||
"files": [
|
||||
{
|
||||
|
||||
+524
@@ -0,0 +1,524 @@
|
||||
<!doctype html>
|
||||
<!-- Demo plate for the catalog preview. Identical to shutter-slam.html except the
|
||||
body background, which is opaque here so the plate reads on the catalog card.
|
||||
Not installed by `hyperframes add` - registry-item.json lists shutter-slam.html only. -->
|
||||
<html
|
||||
lang="en"
|
||||
data-composition-id="shutter-slam"
|
||||
data-composition-duration="6"
|
||||
data-composition-variables='[
|
||||
{ "id": "text", "type": "string", "role": "content", "label": "Word", "description": "The word driven through the six beats.", "default": "MOTION" },
|
||||
{ "id": "accent", "type": "enum", "role": "style", "label": "Accent", "description": "Word color.", "default": "green", "options": [{ "value": "green", "label": "Green" }, { "value": "blue", "label": "Blue" }, { "value": "violet", "label": "Violet" }] },
|
||||
{ "id": "blur", "type": "enum", "role": "motion", "label": "Blur", "description": "Integrate each frame over the shutter window, or capture one instant per frame.", "default": "shutter", "options": [{ "value": "shutter", "label": "Shutter" }, { "value": "none", "label": "None" }] },
|
||||
{ "id": "cues", "type": "string", "role": "motion", "label": "Cues", "description": "Comma seconds from mount start for each of the six beats; empty keeps the authored rhythm.", "default": "" },
|
||||
{ "id": "exit", "type": "enum", "role": "motion", "label": "Exit", "description": "How the word leaves.", "default": "none", "options": [{ "value": "none", "label": "None" }, { "value": "fade", "label": "Fade" }, { "value": "up", "label": "Up" }] }
|
||||
]'
|
||||
>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Shutter Slam</title>
|
||||
</head>
|
||||
<body>
|
||||
<template>
|
||||
<div id="root" data-composition-id="shutter-slam" data-duration="6" data-fps="30">
|
||||
<style>
|
||||
body {
|
||||
background: #06060a;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#root {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
container-type: size;
|
||||
isolation: isolate;
|
||||
font-family: var(--font-display, Inter, system-ui, sans-serif);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ss-clip {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100cqw;
|
||||
height: 100cqh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* The turns need a perspective ancestor, and the blur reads its
|
||||
perspective off the word's own parent, so the stage that carries
|
||||
it must be the word's direct parent. */
|
||||
.ss-stage {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
perspective: 104cqw;
|
||||
}
|
||||
|
||||
.ss-word {
|
||||
color: var(--ss-accent, #71f5a7);
|
||||
font-size: var(--ss-font-size, min(14cqw, 26cqh));
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
letter-spacing: -0.02em;
|
||||
white-space: nowrap;
|
||||
transform-origin: 50% 50%;
|
||||
will-change: transform;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div
|
||||
id="shutter-slam-clip"
|
||||
class="ss-clip clip"
|
||||
data-start="0"
|
||||
data-duration="6"
|
||||
data-track-index="0"
|
||||
>
|
||||
<div class="ss-stage">
|
||||
<div class="ss-word" id="shutter-slam-word" role="heading" aria-level="1"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
function resolveFps(optionFps) {
|
||||
var explicit = Number(optionFps);
|
||||
if (explicit > 0) return explicit;
|
||||
|
||||
var root = document.querySelector("[data-composition-id][data-fps]");
|
||||
var rootFps = root ? Number(root.getAttribute("data-fps")) : 0;
|
||||
if (rootFps > 0) return rootFps;
|
||||
|
||||
return 30;
|
||||
}
|
||||
|
||||
function numOption(value, fallback) {
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
opts = opts || {};
|
||||
var shutterAngle = numOption(opts.shutterAngle, 720);
|
||||
var shutterPhase = numOption(opts.shutterPhase, -360);
|
||||
var requestedSamples = numOption(opts.samplesPerFrame, 16);
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var fps = resolveFps(opts.fps);
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
if (typeof s === "string") {
|
||||
document.querySelectorAll(s).forEach(function (el) {
|
||||
acc.push(el);
|
||||
});
|
||||
} else if (s instanceof Element) {
|
||||
acc.push(s);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function")
|
||||
new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var t0 = tl.time();
|
||||
var duration = tl.duration();
|
||||
var windowStart = t0 + shutterPhase / 360 / fps;
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
tl.time(t0, true);
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
// tl.eventCallback("onUpdate") is unavailable under the HyperFrames runtime proxy, so a
|
||||
// tracker tween's onUpdate fires on every seek. Sampling is deferred to a microtask:
|
||||
// seeking GSAP from inside its own render reads stale tween state, while the microtask
|
||||
// runs after the seek returns and before the frame is captured or painted.
|
||||
var _proxy = { t: 0 };
|
||||
tl.to(
|
||||
_proxy,
|
||||
{
|
||||
t: 1,
|
||||
duration: Math.max(tl.duration(), 0.1),
|
||||
ease: "none",
|
||||
onUpdate: function () {
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
Promise.resolve().then(function () {
|
||||
scheduled = false;
|
||||
applyShutter();
|
||||
});
|
||||
},
|
||||
},
|
||||
0,
|
||||
);
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
<script>
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var root = document.getElementById("root");
|
||||
var word = root.querySelector(".ss-word");
|
||||
var vars =
|
||||
window.__hyperframes && window.__hyperframes.getVariables
|
||||
? window.__hyperframes.getVariables()
|
||||
: {};
|
||||
|
||||
var text = vars.text == null ? "MOTION" : String(vars.text);
|
||||
var accentColors = {
|
||||
green: "var(--brand, #71f5a7)",
|
||||
blue: "var(--accent, #61a8ff)",
|
||||
violet: "var(--accent-2, #b895ff)",
|
||||
};
|
||||
var accent = Object.prototype.hasOwnProperty.call(accentColors, vars.accent)
|
||||
? vars.accent
|
||||
: "green";
|
||||
var blurred = vars.blur !== "none";
|
||||
var exit = vars.exit === "fade" || vars.exit === "up" ? vars.exit : "none";
|
||||
|
||||
root.style.setProperty("--ss-accent", accentColors[accent]);
|
||||
word.textContent = text;
|
||||
|
||||
// One em per character keeps any word inside the box at rest, which is what
|
||||
// the slam amplitudes are measured against; the scale punch is meant to
|
||||
// overflow and the clip crops it.
|
||||
var fittedCqw = Math.min(14, 76 / Math.max(1, Array.from(text).length));
|
||||
root.style.setProperty("--ss-font-size", "min(" + fittedCqw.toFixed(3) + "cqw, 26cqh)");
|
||||
|
||||
// Measured off the reference export; see the header.
|
||||
function aeEase(t) {
|
||||
var X1 = 0.54;
|
||||
var X2 = 0.48;
|
||||
var s = t;
|
||||
for (var i = 0; i < 8; i++) {
|
||||
var x = 3 * X1 * (1 - s) * (1 - s) * s + 3 * X2 * (1 - s) * s * s + s * s * s;
|
||||
var dx =
|
||||
3 * X1 * (1 - 4 * s + 3 * s * s) + 3 * X2 * (2 * s - 3 * s * s) + 3 * s * s;
|
||||
if (Math.abs(dx) < 1e-9) break;
|
||||
s -= (x - t) / dx;
|
||||
if (s < 0) s = 0;
|
||||
else if (s > 1) s = 1;
|
||||
}
|
||||
return 3 * (1 - s) * s * s + s * s * s;
|
||||
}
|
||||
|
||||
var SLAM_X = 32.1; // cqw, the reference's 617 px on a 1920 px frame
|
||||
var SLAM_Y = 30.5; // cqh, its 329 px on a 1080 px frame
|
||||
var SLAM = 0.3;
|
||||
var TURN = 0.6;
|
||||
var TURN_Z = 0.733;
|
||||
// Authored start of each beat, and the end of the last one.
|
||||
var CUES_BASE = [0, 1.2, 2.4, 3.7, 4.5, 5.233];
|
||||
var BEATS_BASE = 5.233 + TURN_Z;
|
||||
var OUT_BASE = exit === "none" ? 0 : 0.4;
|
||||
|
||||
var duration = Math.max(0.001, parseFloat(root.dataset.duration || "6"));
|
||||
var baseTotal = BEATS_BASE + OUT_BASE;
|
||||
var beatScale = duration < baseTotal ? duration / baseTotal : 1;
|
||||
|
||||
// An authored cue list replaces the rhythm outright rather than scaling it,
|
||||
// so a beat locked to narration lands where the narration does. Missing or
|
||||
// unreadable entries keep their authored start.
|
||||
var authored = String(vars.cues == null ? "" : vars.cues)
|
||||
.split(",")
|
||||
.map(function (part) {
|
||||
return parseFloat(part.trim());
|
||||
});
|
||||
var cues = CUES_BASE.map(function (base, index) {
|
||||
var value = authored[index];
|
||||
return Number.isFinite(value) ? value : base * beatScale;
|
||||
});
|
||||
|
||||
var tl = gsap.timeline({ paused: true, defaults: { ease: aeEase } });
|
||||
var slam = SLAM * beatScale;
|
||||
var turn = TURN * beatScale;
|
||||
var turnZ = TURN_Z * beatScale;
|
||||
|
||||
// Beat 1 — translate X, out and back twice.
|
||||
tl.to(word, { x: SLAM_X + "cqw", duration: slam }, cues[0])
|
||||
.to(word, { x: -SLAM_X + "cqw", duration: slam }, cues[0] + slam)
|
||||
.to(word, { x: SLAM_X + "cqw", duration: slam }, cues[0] + slam * 2)
|
||||
.to(word, { x: 0, duration: slam }, cues[0] + slam * 3);
|
||||
|
||||
// Beat 2 — translate Y, up first.
|
||||
tl.to(word, { y: -SLAM_Y + "cqh", duration: slam }, cues[1])
|
||||
.to(word, { y: SLAM_Y + "cqh", duration: slam }, cues[1] + slam)
|
||||
.to(word, { y: -SLAM_Y + "cqh", duration: slam }, cues[1] + slam * 2)
|
||||
.to(word, { y: 0, duration: slam }, cues[1] + slam * 3);
|
||||
|
||||
// Beat 3 — scale punch, up then down then up.
|
||||
tl.to(word, { scale: 4.04, duration: slam }, cues[2])
|
||||
.to(word, { scale: 0.466, duration: slam }, cues[2] + slam)
|
||||
.to(word, { scale: 4.04, duration: slam }, cues[2] + slam * 2)
|
||||
.to(word, { scale: 1, duration: slam }, cues[2] + slam * 3);
|
||||
|
||||
// Beats 4 to 6 — one full turn about each axis. A full turn ends where it
|
||||
// started, so each is a single tween rather than an out-and-back pair.
|
||||
tl.to(word, { rotationX: 360, duration: turn }, cues[3]);
|
||||
tl.to(word, { rotationY: 360, duration: turn }, cues[4]);
|
||||
tl.to(word, { rotation: 360, duration: turnZ }, cues[5]);
|
||||
|
||||
var beatsEnd = Math.max.apply(
|
||||
null,
|
||||
cues
|
||||
.slice(0, 3)
|
||||
.map(function (cue) {
|
||||
return cue + slam * 4;
|
||||
})
|
||||
.concat([cues[3] + turn, cues[4] + turn, cues[5] + turnZ]),
|
||||
);
|
||||
var outStart = Math.max(beatsEnd, duration - OUT_BASE * beatScale);
|
||||
|
||||
if (exit !== "none") {
|
||||
tl.to(
|
||||
word,
|
||||
{
|
||||
opacity: 0,
|
||||
y: exit === "up" ? "-12cqh" : 0,
|
||||
duration: OUT_BASE * beatScale,
|
||||
ease: "power2.in",
|
||||
},
|
||||
outStart,
|
||||
);
|
||||
}
|
||||
|
||||
// Seeks past the last tween must still reach the blur's tracker, so the
|
||||
// timeline runs to the mount's full duration.
|
||||
tl.set({}, {}, duration);
|
||||
|
||||
// After every tween, before registration: the tracker tween the blur adds
|
||||
// needs the timeline's final duration.
|
||||
if (blurred) attachMotionBlur(word, tl, { fps: 30 });
|
||||
|
||||
tl.seek(0);
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["shutter-slam"] = tl;
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</template>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"$schema": "https://hyperframes.heygen.com/schema/registry-item.json",
|
||||
"name": "shutter-slam",
|
||||
"type": "hyperframes:component",
|
||||
"title": "Shutter Slam",
|
||||
"description": "One word thrown through six single-property beats under integrated shutter blur — two translate slams, a scale punch, then a full turn about each axis — on the measured easing of the After Effects export the shutter model was fitted to",
|
||||
"tags": ["effect", "motion-blur", "shutter", "after-effects", "slam", "animation"],
|
||||
"files": [
|
||||
{
|
||||
"path": "shutter-slam.html",
|
||||
"target": "compositions/components/shutter-slam.html",
|
||||
"type": "hyperframes:snippet"
|
||||
}
|
||||
],
|
||||
"preview": {
|
||||
"poster": "https://static.heygen.ai/hyperframes-oss/docs/images/catalog/components/shutter-slam.png"
|
||||
}
|
||||
}
|
||||
+541
@@ -0,0 +1,541 @@
|
||||
<!doctype html>
|
||||
<!--
|
||||
shutter-slam: HyperFrames video primitive
|
||||
|
||||
One word thrown through six single-property beats, every frame integrated
|
||||
over the camera shutter: two hard translate slams, a scale punch, then a
|
||||
full turn about each of the three axes. It is the motion-blur primitive's
|
||||
reference case — the beats are the ones measured off the After Effects
|
||||
export the shutter model was fitted to, so every driver the model covers
|
||||
(translate, scale, rotate, 3D rotate) is exercised in one mount.
|
||||
|
||||
Variables:
|
||||
text: the slammed word
|
||||
accent: green, blue, or violet word color
|
||||
blur: shutter (integrated) or none (one instant per frame)
|
||||
cues: comma seconds from mount start for each of the six beats
|
||||
exit: none, fade, or up
|
||||
|
||||
Envelope, fixed beats with elastic HOLD:
|
||||
BEATS = 5.97s at the authored rhythm (0.3s per slam, 0.6s per 3D turn,
|
||||
0.73s for the Z turn)
|
||||
HOLD = max(0, D - BEATS - OUT), the word at rest
|
||||
OUT = 0.40s when exit is fade or up, else 0
|
||||
If D is shorter than BEATS + OUT the beat clock compresses; the timeline
|
||||
is never time-scaled.
|
||||
|
||||
Easing is power2.inOut because it measured best, not because it was the
|
||||
default. A bezier fitted to the reference's own bbox centres looks like the
|
||||
better curve on paper and renders worse: 1.3 dB down on the horizontal slam,
|
||||
1.0 dB up on the vertical turn, 0.25 dB down over the clip. A blurred bbox
|
||||
centre is the shutter window's average, not the instant, so on an
|
||||
accelerating segment the fit is measuring its own blur.
|
||||
|
||||
Amplitudes are fractions of the host box (32.1cqw, 30.5cqh), so the slams
|
||||
leave the frame on a wide mount exactly as far as they do on the reference.
|
||||
The scale punch overflows on purpose; the clip crops it.
|
||||
|
||||
Mount contract: the runtime clones only this template. #root fills the host
|
||||
box, establishes the container query basis, and has no data-width or
|
||||
data-height. One paused timeline registers under the literal shutter-slam
|
||||
key.
|
||||
-->
|
||||
<html
|
||||
lang="en"
|
||||
data-composition-id="shutter-slam"
|
||||
data-composition-duration="6"
|
||||
data-composition-variables='[
|
||||
{ "id": "text", "type": "string", "role": "content", "label": "Word", "description": "The word driven through the six beats.", "default": "MOTION" },
|
||||
{ "id": "accent", "type": "enum", "role": "style", "label": "Accent", "description": "Word color.", "default": "green", "options": [{ "value": "green", "label": "Green" }, { "value": "blue", "label": "Blue" }, { "value": "violet", "label": "Violet" }] },
|
||||
{ "id": "blur", "type": "enum", "role": "motion", "label": "Blur", "description": "Integrate each frame over the shutter window, or capture one instant per frame.", "default": "shutter", "options": [{ "value": "shutter", "label": "Shutter" }, { "value": "none", "label": "None" }] },
|
||||
{ "id": "cues", "type": "string", "role": "motion", "label": "Cues", "description": "Comma seconds from mount start for each of the six beats; empty keeps the authored rhythm.", "default": "" },
|
||||
{ "id": "exit", "type": "enum", "role": "motion", "label": "Exit", "description": "How the word leaves.", "default": "none", "options": [{ "value": "none", "label": "None" }, { "value": "fade", "label": "Fade" }, { "value": "up", "label": "Up" }] }
|
||||
]'
|
||||
>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Shutter Slam</title>
|
||||
</head>
|
||||
<body>
|
||||
<template>
|
||||
<div id="root" data-composition-id="shutter-slam" data-duration="6" data-fps="30">
|
||||
<style>
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#root {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
container-type: size;
|
||||
isolation: isolate;
|
||||
font-family: var(--font-display, Inter, system-ui, sans-serif);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ss-clip {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100cqw;
|
||||
height: 100cqh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* The turns need a perspective ancestor, and the blur reads its
|
||||
perspective off the word's own parent, so the stage that carries
|
||||
it must be the word's direct parent. */
|
||||
.ss-stage {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
perspective: 104cqw;
|
||||
}
|
||||
|
||||
.ss-word {
|
||||
color: var(--ss-accent, #71f5a7);
|
||||
font-size: var(--ss-font-size, min(14cqw, 26cqh));
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
letter-spacing: -0.02em;
|
||||
white-space: nowrap;
|
||||
transform-origin: 50% 50%;
|
||||
will-change: transform;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div
|
||||
id="shutter-slam-clip"
|
||||
class="ss-clip clip"
|
||||
data-start="0"
|
||||
data-duration="6"
|
||||
data-track-index="0"
|
||||
>
|
||||
<div class="ss-stage">
|
||||
<div class="ss-word" id="shutter-slam-word" role="heading" aria-level="1"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
function resolveFps(optionFps) {
|
||||
var explicit = Number(optionFps);
|
||||
if (explicit > 0) return explicit;
|
||||
|
||||
var root = document.querySelector("[data-composition-id][data-fps]");
|
||||
var rootFps = root ? Number(root.getAttribute("data-fps")) : 0;
|
||||
if (rootFps > 0) return rootFps;
|
||||
|
||||
return 30;
|
||||
}
|
||||
|
||||
function numOption(value, fallback) {
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
opts = opts || {};
|
||||
var shutterAngle = numOption(opts.shutterAngle, 720);
|
||||
var shutterPhase = numOption(opts.shutterPhase, -360);
|
||||
var requestedSamples = numOption(opts.samplesPerFrame, 16);
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var fps = resolveFps(opts.fps);
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
if (typeof s === "string") {
|
||||
document.querySelectorAll(s).forEach(function (el) {
|
||||
acc.push(el);
|
||||
});
|
||||
} else if (s instanceof Element) {
|
||||
acc.push(s);
|
||||
}
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function")
|
||||
new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var t0 = tl.time();
|
||||
var duration = tl.duration();
|
||||
var windowStart = t0 + shutterPhase / 360 / fps;
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
tl.time(t0, true);
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
// tl.eventCallback("onUpdate") is unavailable under the HyperFrames runtime proxy, so a
|
||||
// tracker tween's onUpdate fires on every seek. Sampling is deferred to a microtask:
|
||||
// seeking GSAP from inside its own render reads stale tween state, while the microtask
|
||||
// runs after the seek returns and before the frame is captured or painted.
|
||||
var _proxy = { t: 0 };
|
||||
tl.to(
|
||||
_proxy,
|
||||
{
|
||||
t: 1,
|
||||
duration: Math.max(tl.duration(), 0.1),
|
||||
ease: "none",
|
||||
onUpdate: function () {
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
Promise.resolve().then(function () {
|
||||
scheduled = false;
|
||||
applyShutter();
|
||||
});
|
||||
},
|
||||
},
|
||||
0,
|
||||
);
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
<script>
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var root = document.getElementById("root");
|
||||
var word = root.querySelector(".ss-word");
|
||||
var vars =
|
||||
window.__hyperframes && window.__hyperframes.getVariables
|
||||
? window.__hyperframes.getVariables()
|
||||
: {};
|
||||
|
||||
var text = vars.text == null ? "MOTION" : String(vars.text);
|
||||
var accentColors = {
|
||||
green: "var(--brand, #71f5a7)",
|
||||
blue: "var(--accent, #61a8ff)",
|
||||
violet: "var(--accent-2, #b895ff)",
|
||||
};
|
||||
var accent = Object.prototype.hasOwnProperty.call(accentColors, vars.accent)
|
||||
? vars.accent
|
||||
: "green";
|
||||
var blurred = vars.blur !== "none";
|
||||
var exit = vars.exit === "fade" || vars.exit === "up" ? vars.exit : "none";
|
||||
|
||||
root.style.setProperty("--ss-accent", accentColors[accent]);
|
||||
word.textContent = text;
|
||||
|
||||
// One em per character keeps any word inside the box at rest, which is what
|
||||
// the slam amplitudes are measured against; the scale punch is meant to
|
||||
// overflow and the clip crops it.
|
||||
var fittedCqw = Math.min(14, 76 / Math.max(1, Array.from(text).length));
|
||||
root.style.setProperty("--ss-font-size", "min(" + fittedCqw.toFixed(3) + "cqw, 26cqh)");
|
||||
|
||||
// Measured best, not defaulted. A bezier fitted to the reference's own bbox
|
||||
// centres renders 0.25 dB worse over the clip, because a blurred bbox centre
|
||||
// is the shutter window's average rather than the instant. See the header.
|
||||
var EASE = "power2.inOut";
|
||||
var SLAM_X = 32.1; // cqw, the reference's 617 px on a 1920 px frame
|
||||
var SLAM_Y = 30.5; // cqh, its 329 px on a 1080 px frame
|
||||
var SLAM = 0.3;
|
||||
var TURN = 0.6;
|
||||
var TURN_Z = 0.733;
|
||||
// Authored start of each beat.
|
||||
var CUES_BASE = [0, 1.2, 2.4, 3.7, 4.5, 5.233];
|
||||
var BEATS_BASE = CUES_BASE[5] + TURN_Z;
|
||||
var OUT_BASE = exit === "none" ? 0 : 0.4;
|
||||
|
||||
var duration = Math.max(0.001, parseFloat(root.dataset.duration || "6"));
|
||||
var baseTotal = BEATS_BASE + OUT_BASE;
|
||||
var beatScale = duration < baseTotal ? duration / baseTotal : 1;
|
||||
|
||||
var slam = SLAM * beatScale;
|
||||
var turn = TURN * beatScale;
|
||||
var turnZ = TURN_Z * beatScale;
|
||||
var out = OUT_BASE * beatScale;
|
||||
// How long each beat runs, in beat order.
|
||||
var LENGTHS = [slam * 4, slam * 4, slam * 4, turn, turn, turnZ];
|
||||
|
||||
// An authored cue replaces the rhythm rather than scaling it, so a beat locked
|
||||
// to narration lands where the narration does. A missing or unreadable entry
|
||||
// keeps its authored start; one that would run its beat past the mount is
|
||||
// pulled back to end on the last frame, since past the end it never renders.
|
||||
var authored = String(vars.cues == null ? "" : vars.cues)
|
||||
.split(",")
|
||||
.map(function (part) {
|
||||
return parseFloat(part.trim());
|
||||
});
|
||||
var cues = CUES_BASE.map(function (base, index) {
|
||||
var value = authored[index];
|
||||
if (!Number.isFinite(value)) return base * beatScale;
|
||||
return Math.min(Math.max(value, 0), Math.max(0, duration - out - LENGTHS[index]));
|
||||
});
|
||||
|
||||
var tl = gsap.timeline({ paused: true, defaults: { ease: EASE } });
|
||||
|
||||
// Beat 1 — translate X, out and back twice.
|
||||
tl.to(word, { x: SLAM_X + "cqw", duration: slam }, cues[0])
|
||||
.to(word, { x: -SLAM_X + "cqw", duration: slam }, cues[0] + slam)
|
||||
.to(word, { x: SLAM_X + "cqw", duration: slam }, cues[0] + slam * 2)
|
||||
.to(word, { x: 0, duration: slam }, cues[0] + slam * 3);
|
||||
|
||||
// Beat 2 — translate Y, up first.
|
||||
tl.to(word, { y: -SLAM_Y + "cqh", duration: slam }, cues[1])
|
||||
.to(word, { y: SLAM_Y + "cqh", duration: slam }, cues[1] + slam)
|
||||
.to(word, { y: -SLAM_Y + "cqh", duration: slam }, cues[1] + slam * 2)
|
||||
.to(word, { y: 0, duration: slam }, cues[1] + slam * 3);
|
||||
|
||||
// Beat 3 — scale punch, up then down then up.
|
||||
tl.to(word, { scale: 4.04, duration: slam }, cues[2])
|
||||
.to(word, { scale: 0.466, duration: slam }, cues[2] + slam)
|
||||
.to(word, { scale: 4.04, duration: slam }, cues[2] + slam * 2)
|
||||
.to(word, { scale: 1, duration: slam }, cues[2] + slam * 3);
|
||||
|
||||
// Beats 4 to 6 — one full turn about each axis. A full turn ends where it
|
||||
// started, so each is a single tween rather than an out-and-back pair.
|
||||
tl.to(word, { rotationX: 360, duration: turn }, cues[3]);
|
||||
tl.to(word, { rotationY: 360, duration: turn }, cues[4]);
|
||||
tl.to(word, { rotation: 360, duration: turnZ }, cues[5]);
|
||||
|
||||
var beatsEnd = Math.max.apply(
|
||||
null,
|
||||
cues.map(function (cue, index) {
|
||||
return cue + LENGTHS[index];
|
||||
}),
|
||||
);
|
||||
var outStart = Math.max(beatsEnd, duration - out);
|
||||
|
||||
if (exit !== "none") {
|
||||
var leaving = { opacity: 0, duration: out, ease: "power2.in" };
|
||||
if (exit === "up") leaving.y = "-12cqh";
|
||||
tl.to(word, leaving, outStart);
|
||||
}
|
||||
|
||||
// Seeks past the last tween must still reach the blur's tracker, so the
|
||||
// timeline runs to the mount's full duration.
|
||||
tl.set(document.body, {}, duration);
|
||||
|
||||
// After every tween, before registration: the tracker tween the blur adds
|
||||
// needs the timeline's final duration.
|
||||
if (blurred) attachMotionBlur(word, tl, { fps: 30 });
|
||||
|
||||
tl.seek(0);
|
||||
window.__timelines = window.__timelines || {};
|
||||
window.__timelines["shutter-slam"] = tl;
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</template>
|
||||
</body>
|
||||
</html>
|
||||
+173
-155
@@ -343,6 +343,7 @@
|
||||
(function () {
|
||||
/* ── attachMotionBlur ─────────────────────────────────────── */
|
||||
if (!window._hfMbUid) window._hfMbUid = 0;
|
||||
if (!window._hfMbAttached) window._hfMbAttached = new WeakSet();
|
||||
|
||||
// Shutter length is measured in frames, so the snippet must know the
|
||||
// composition frame rate: explicit option, else the root's data-fps, else 30.
|
||||
@@ -361,9 +362,55 @@
|
||||
return value !== undefined ? Number(value) : fallback;
|
||||
}
|
||||
|
||||
// objectBoundingBox percentage for a px offset plus padding.
|
||||
function regionPercent(offset, size, padPercent) {
|
||||
return ((offset / size) * 100 + padPercent).toFixed(2) + "%";
|
||||
// A resolved `transform` is either "none", a 2D matrix(a,b,c,d,e,f) or a 3D
|
||||
// matrix3d of 16. Splitting the numbers into the linear part and the
|
||||
// translation is what lets the deadband below use a pixel tolerance on the
|
||||
// one and an angle/ratio tolerance on the other.
|
||||
function parseTransform(value) {
|
||||
if (!value || value === "none") return { linear: [1, 0, 0, 1], translate: [0, 0, 0] };
|
||||
var nums = value
|
||||
.slice(value.indexOf("(") + 1, -1)
|
||||
.split(",")
|
||||
.map(parseFloat);
|
||||
if (nums.length === 16) {
|
||||
return {
|
||||
linear: [
|
||||
nums[0],
|
||||
nums[1],
|
||||
nums[2],
|
||||
nums[4],
|
||||
nums[5],
|
||||
nums[6],
|
||||
nums[8],
|
||||
nums[9],
|
||||
nums[10],
|
||||
nums[3],
|
||||
nums[7],
|
||||
nums[11],
|
||||
nums[15],
|
||||
],
|
||||
translate: [nums[12], nums[13], nums[14]],
|
||||
};
|
||||
}
|
||||
return {
|
||||
linear: [nums[0], nums[1], nums[2], nums[3]],
|
||||
translate: [nums[4], nums[5], 0],
|
||||
};
|
||||
}
|
||||
|
||||
// Deadband: half a pixel of travel, a thousandth of a unit of linear change,
|
||||
// about 0.06 degrees or 0.1% of scale. Below it the average is the source.
|
||||
// The 2D and 3D forms have different arities, so a change of form counts as
|
||||
// movement rather than being compared component by component.
|
||||
function differs(a, b) {
|
||||
if (a.linear.length !== b.linear.length) return true;
|
||||
for (var i = 0; i < a.linear.length; i++) {
|
||||
if (Math.abs(a.linear[i] - b.linear[i]) > 0.001) return true;
|
||||
}
|
||||
for (var j = 0; j < 3; j++) {
|
||||
if (Math.abs(a.translate[j] - b.translate[j]) > 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
window.attachMotionBlur = function (selector, tl, opts) {
|
||||
@@ -374,49 +421,7 @@
|
||||
var samples = Number.isFinite(requestedSamples)
|
||||
? Math.max(2, Math.min(64, Math.round(requestedSamples)))
|
||||
: 16;
|
||||
var axis = opts.axis || "both";
|
||||
var fps = resolveFps(opts.fps);
|
||||
var useX = axis !== "y";
|
||||
var useY = axis !== "x";
|
||||
|
||||
// Untransformed box size; SVG elements have no offsetWidth, so use the
|
||||
// same bbox GSAP uses to resolve their percent transforms.
|
||||
function boxSize(el, horizontal) {
|
||||
var box = typeof el.offsetWidth === "number" ? el : el.getBBox ? el.getBBox() : null;
|
||||
var size = box
|
||||
? horizontal
|
||||
? box.offsetWidth || box.width
|
||||
: box.offsetHeight || box.height
|
||||
: 0;
|
||||
return size || el.getBoundingClientRect()[horizontal ? "width" : "height"] || 1;
|
||||
}
|
||||
|
||||
// GSAP x/y may carry a % unit and xPercent/yPercent is a separate term;
|
||||
// resolve both against the element's own box so samples are in px.
|
||||
function readAxis(el, prop, percentProp, size) {
|
||||
var px = parseFloat(gsap.getProperty(el, prop, "px")) || 0;
|
||||
var percent = parseFloat(gsap.getProperty(el, percentProp)) || 0;
|
||||
return px + (percent * size) / 100;
|
||||
}
|
||||
|
||||
function readPosition(el) {
|
||||
return {
|
||||
x: useX ? readAxis(el, "x", "xPercent", boxSize(el, true)) : 0,
|
||||
y: useY ? readAxis(el, "y", "yPercent", boxSize(el, false)) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
// CSS filters run in the element's pre-transform space while GSAP x/y are
|
||||
// post-transform, so a displacement is mapped through the inverse of the
|
||||
// element's own scale/rotation. Ancestor transforms are not compensated.
|
||||
function toFilterSpace(el, dx, dy) {
|
||||
var sx = parseFloat(gsap.getProperty(el, "scaleX")) || 1;
|
||||
var sy = parseFloat(gsap.getProperty(el, "scaleY")) || 1;
|
||||
var theta = ((parseFloat(gsap.getProperty(el, "rotation")) || 0) * Math.PI) / 180;
|
||||
var cos = Math.cos(theta);
|
||||
var sin = Math.sin(theta);
|
||||
return { dx: (dx * cos + dy * sin) / sx, dy: (-dx * sin + dy * cos) / sy };
|
||||
}
|
||||
|
||||
var items = Array.isArray(selector) ? selector : [selector];
|
||||
var targets = items.reduce(function (acc, s) {
|
||||
@@ -430,83 +435,103 @@
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
var ns = "http://www.w3.org/2000/svg";
|
||||
// `samples` counts sub-intervals of the shutter window, so there is one copy at
|
||||
// every interval boundary — both ends of the window included — and each carries
|
||||
// 1/samples of the source. That is what the reference export shows: the outermost
|
||||
// copy sits exactly one frame away from the frame time, not half a step short.
|
||||
var copies = samples + 1;
|
||||
var weight = String(1 / samples);
|
||||
var alpha = String(1 / samples);
|
||||
|
||||
// One SVG filter per target: N+1 offset copies of SourceGraphic added at 1/N
|
||||
// each, then the element itself over the top. Accumulating in sRGB matches
|
||||
// AE's default (non-linear) 8-bpc working space.
|
||||
var state = targets.map(function (el) {
|
||||
var uid = "hf-mb-" + window._hfMbUid++;
|
||||
var svg = document.createElementNS(ns, "svg");
|
||||
svg.setAttribute("style", "position:absolute;width:0;height:0;overflow:hidden;");
|
||||
|
||||
var filter = document.createElementNS(ns, "filter");
|
||||
filter.id = uid;
|
||||
filter.setAttribute("color-interpolation-filters", "sRGB");
|
||||
|
||||
var offsets = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var feOff = document.createElementNS(ns, "feOffset");
|
||||
feOff.setAttribute("in", "SourceGraphic");
|
||||
feOff.setAttribute("dx", "0");
|
||||
feOff.setAttribute("dy", "0");
|
||||
feOff.setAttribute("result", "s" + k);
|
||||
filter.appendChild(feOff);
|
||||
offsets.push(feOff);
|
||||
// A copy is styled by nothing that selected the original: dropping the id also
|
||||
// drops every `#id` rule that gave it size, colour and font. So each copy carries
|
||||
// its own resolved style inline. Chrome returns "" for a computed style's cssText,
|
||||
// so the declarations are enumerated rather than taken wholesale.
|
||||
function resolvedStyles(source, out) {
|
||||
var cs = getComputedStyle(source);
|
||||
var text = "";
|
||||
for (var i = 0; i < cs.length; i++) {
|
||||
text += cs[i] + ":" + cs.getPropertyValue(cs[i]) + ";";
|
||||
}
|
||||
|
||||
// Pairwise accumulation: the first composite scales both inputs by 1/N, every
|
||||
// later one adds the next copy at 1/N to the running sum. The N+1 weights total
|
||||
// (N+1)/N, so an element wider than its own smear saturates through the middle
|
||||
// and the filter clamps there. That is the saturation the reference shows, and
|
||||
// the sharp instance covers the same region regardless.
|
||||
var accumulated = "s0";
|
||||
for (var c = 1; c < copies; c++) {
|
||||
var feComp = document.createElementNS(ns, "feComposite");
|
||||
feComp.setAttribute("operator", "arithmetic");
|
||||
feComp.setAttribute("in", accumulated);
|
||||
feComp.setAttribute("in2", "s" + c);
|
||||
feComp.setAttribute("k1", "0");
|
||||
feComp.setAttribute("k2", c === 1 ? weight : "1");
|
||||
feComp.setAttribute("k3", weight);
|
||||
feComp.setAttribute("k4", "0");
|
||||
accumulated = "a" + c;
|
||||
feComp.setAttribute("result", accumulated);
|
||||
filter.appendChild(feComp);
|
||||
// A copy is a still of one instant. Left live, an inherited transition or
|
||||
// keyframe animation would carry it somewhere the timeline never sampled.
|
||||
out.push(text + "transition:none;animation:none;");
|
||||
for (var c = 0; c < source.children.length; c++) {
|
||||
resolvedStyles(source.children[c], out);
|
||||
}
|
||||
|
||||
// The frame-time instance is drawn sharp, at full opacity, over the smear.
|
||||
// Every blurred copy stays at 1/N, so nothing but the instance the frame is
|
||||
// actually at reads as solid. Unnamed, so it is the filter output.
|
||||
var feOver = document.createElementNS(ns, "feComposite");
|
||||
feOver.setAttribute("operator", "over");
|
||||
feOver.setAttribute("in", "SourceGraphic");
|
||||
feOver.setAttribute("in2", accumulated);
|
||||
filter.appendChild(feOver);
|
||||
|
||||
svg.appendChild(filter);
|
||||
document.body.appendChild(svg);
|
||||
|
||||
return { el: el, offsets: offsets, filter: filter, filterId: uid, xs: [], ys: [] };
|
||||
});
|
||||
|
||||
// The element may carry its own inline filter (authored or tweened by
|
||||
// GSAP); the blur is appended to that chain and removed from it, never
|
||||
// written over it.
|
||||
var OWN_FILTER = /\s*url\(["']?#hf-mb-\d+["']?\)/g;
|
||||
|
||||
function baseFilter(el) {
|
||||
return el.style.filter.replace(OWN_FILTER, "").trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
function clearBlur(s) {
|
||||
s.el.style.filter = baseFilter(s.el);
|
||||
function paintResolvedStyles(copy, styles, cursor) {
|
||||
copy.style.cssText = styles[cursor.i++];
|
||||
for (var c = 0; c < copy.children.length; c++) {
|
||||
paintResolvedStyles(copy.children[c], styles, cursor);
|
||||
}
|
||||
}
|
||||
|
||||
// Perspective applies to a parent's children only, and a copy is a grandchild.
|
||||
// Sharing the parent's 3D context would need preserve-3d on the group, which
|
||||
// mix-blend-mode flattens, so each copy carries the perspective itself. See the
|
||||
// header for what that does to the vanishing point.
|
||||
function parentPerspective(el) {
|
||||
var value = el.parentNode ? getComputedStyle(el.parentNode).perspective : "none";
|
||||
return value && value !== "none" ? "perspective(" + value + ") " : "";
|
||||
}
|
||||
|
||||
var state = targets
|
||||
.filter(function (el) {
|
||||
// One group per element. A second call on the same element would stack a
|
||||
// second set of copies over the first and double the ink, so the first
|
||||
// call owns it.
|
||||
if (window._hfMbAttached.has(el)) return false;
|
||||
window._hfMbAttached.add(el);
|
||||
return true;
|
||||
})
|
||||
.map(function (el) {
|
||||
var group = document.createElement("div");
|
||||
group.setAttribute("data-hf-motion-blur", "hf-mb-" + window._hfMbUid++);
|
||||
group.style.cssText =
|
||||
"position:absolute;left:0;top:0;width:0;height:0;isolation:isolate;pointer-events:none;display:none;";
|
||||
|
||||
var clones = [];
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var clone = el.cloneNode(true);
|
||||
clone.removeAttribute("id");
|
||||
clones.push(clone);
|
||||
group.appendChild(clone);
|
||||
}
|
||||
el.parentNode.insertBefore(group, el);
|
||||
|
||||
var s = { el: el, group: group, clones: clones, samples: [], perspective: "" };
|
||||
|
||||
// Resolved styles and the parent's perspective are px once read, so a
|
||||
// container-relative element needs them again when its box changes. Per frame
|
||||
// that would walk the whole subtree once per copy; on resize it costs nothing
|
||||
// on a fixed-size render and keeps a live preview honest.
|
||||
function snapshot() {
|
||||
var styles = resolvedStyles(el, []);
|
||||
s.perspective = parentPerspective(el);
|
||||
for (var c = 0; c < clones.length; c++) {
|
||||
paintResolvedStyles(clones[c], styles, { i: 0 });
|
||||
clones[c].style.position = "absolute";
|
||||
clones[c].style.margin = "0";
|
||||
clones[c].style.opacity = alpha;
|
||||
clones[c].style.mixBlendMode = "plus-lighter";
|
||||
}
|
||||
}
|
||||
|
||||
snapshot();
|
||||
if (typeof ResizeObserver === "function") new ResizeObserver(snapshot).observe(el);
|
||||
return s;
|
||||
});
|
||||
|
||||
function readTransform(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
return {
|
||||
css: cs.transform,
|
||||
origin: cs.transformOrigin,
|
||||
opacity: cs.opacity,
|
||||
parsed: parseTransform(cs.transform),
|
||||
};
|
||||
}
|
||||
|
||||
var scheduled = false;
|
||||
@@ -514,7 +539,9 @@
|
||||
function applyShutter() {
|
||||
var shutterTime = shutterAngle / 360 / fps;
|
||||
if (!(shutterTime > 0)) {
|
||||
state.forEach(clearBlur);
|
||||
state.forEach(function (s) {
|
||||
s.group.style.display = "none";
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -524,15 +551,13 @@
|
||||
|
||||
// Sample the real trajectory: seek to each sub-frame time with events
|
||||
// suppressed (so no tween callbacks, including this tracker's, fire),
|
||||
// read positions, then restore the frame time.
|
||||
// read the resolved transform, then restore the frame time.
|
||||
try {
|
||||
for (var k = 0; k < copies; k++) {
|
||||
var tk = windowStart + (k / samples) * shutterTime;
|
||||
tl.time(Math.min(duration, Math.max(0, tk)), true);
|
||||
state.forEach(function (s) {
|
||||
var pos = readPosition(s.el);
|
||||
s.xs[k] = pos.x;
|
||||
s.ys[k] = pos.y;
|
||||
s.samples[k] = readTransform(s.el);
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
@@ -540,48 +565,42 @@
|
||||
}
|
||||
|
||||
state.forEach(function (s) {
|
||||
var current = readPosition(s.el);
|
||||
var minDx = Infinity;
|
||||
var maxDx = -Infinity;
|
||||
var minDy = Infinity;
|
||||
var maxDy = -Infinity;
|
||||
var current = readTransform(s.el);
|
||||
var moved = false;
|
||||
for (var i = 0; i < copies; i++) {
|
||||
var d = toFilterSpace(s.el, s.xs[i] - current.x, s.ys[i] - current.y);
|
||||
var dx = d.dx;
|
||||
var dy = d.dy;
|
||||
s.offsets[i].setAttribute("dx", dx.toFixed(3));
|
||||
s.offsets[i].setAttribute("dy", dy.toFixed(3));
|
||||
if (dx < minDx) minDx = dx;
|
||||
if (dx > maxDx) maxDx = dx;
|
||||
if (dy < minDy) minDy = dy;
|
||||
if (dy > maxDy) maxDy = dy;
|
||||
if (differs(s.samples[i].parsed, current.parsed)) {
|
||||
moved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Below half a pixel of smear the average is indistinguishable from
|
||||
// the source — render sharp instead of paying for the filter.
|
||||
if (maxDx - minDx < 0.5 && maxDy - minDy < 0.5) {
|
||||
clearBlur(s);
|
||||
if (!moved) {
|
||||
s.group.style.display = "none";
|
||||
return;
|
||||
}
|
||||
|
||||
// Grow the filter region to cover every copy AND the sharp instance the
|
||||
// final composite draws at offset 0 (objectBoundingBox units, 10% padding
|
||||
// so anti-aliased edges are not clipped). Clamping the bounds through 0
|
||||
// matters whenever the window sits entirely on one side of the frame time
|
||||
// — any shutterPhase above 0 or below -shutterAngle — because then no copy
|
||||
// is at 0 and a region derived from the copies alone cuts the instance off.
|
||||
var x0 = Math.min(0, minDx);
|
||||
var x1 = Math.max(0, maxDx);
|
||||
var y0 = Math.min(0, minDy);
|
||||
var y1 = Math.max(0, maxDy);
|
||||
var w = boxSize(s.el, true);
|
||||
var h = boxSize(s.el, false);
|
||||
s.filter.setAttribute("x", regionPercent(x0, w, -10));
|
||||
s.filter.setAttribute("width", regionPercent(x1 - x0, w, 120));
|
||||
s.filter.setAttribute("y", regionPercent(y0, h, -10));
|
||||
s.filter.setAttribute("height", regionPercent(y1 - y0, h, 120));
|
||||
var base = baseFilter(s.el);
|
||||
s.el.style.filter = (base ? base + " " : "") + "url(#" + s.filterId + ")";
|
||||
// The copies are absolutely positioned inside the group, and the group sits at
|
||||
// the origin of the element's own containing block, so the element's offset box
|
||||
// places them. Re-read every frame: a beat is free to move the box itself.
|
||||
var left = s.el.offsetLeft + "px";
|
||||
var top = s.el.offsetTop + "px";
|
||||
var width = s.el.offsetWidth + "px";
|
||||
var height = s.el.offsetHeight + "px";
|
||||
for (var j = 0; j < copies; j++) {
|
||||
var clone = s.clones[j];
|
||||
clone.style.left = left;
|
||||
clone.style.top = top;
|
||||
clone.style.width = width;
|
||||
clone.style.height = height;
|
||||
clone.style.transformOrigin = s.samples[j].origin;
|
||||
clone.style.transform =
|
||||
s.perspective + (s.samples[j].css === "none" ? "" : s.samples[j].css);
|
||||
}
|
||||
// The copies are the element's own ink, so they have to carry its opacity too:
|
||||
// a beat that moves and fades at once would otherwise leave a full-strength
|
||||
// smear behind a vanishing element. It rides the group, not the copies, whose
|
||||
// own opacity is the 1/N shutter weight.
|
||||
s.group.style.opacity = current.opacity;
|
||||
s.group.style.display = "";
|
||||
});
|
||||
}
|
||||
|
||||
@@ -629,7 +648,6 @@
|
||||
attachMotionBlur(
|
||||
["#s1", "#s2", "#s3", "#s4", "#s5", "#t1", "#t2", "#t3", "#t4", "#t5"],
|
||||
tl,
|
||||
{ axis: "x" },
|
||||
);
|
||||
|
||||
window.__timelines = window.__timelines || {};
|
||||
|
||||
@@ -1363,6 +1363,10 @@
|
||||
"name": "shimmer-sweep",
|
||||
"type": "hyperframes:component"
|
||||
},
|
||||
{
|
||||
"name": "shutter-slam",
|
||||
"type": "hyperframes:component"
|
||||
},
|
||||
{
|
||||
"name": "signup-flow",
|
||||
"type": "hyperframes:component"
|
||||
@@ -1637,6 +1641,6 @@
|
||||
}
|
||||
],
|
||||
"catalogArtifact": {
|
||||
"revision": "34370735fa1a93099519873178e547c43b14f3bd69491013577515f4bb4f5957"
|
||||
"revision": "e1c1f6eb5505d4b68d8240850425465c8375fed95b0d30b31328a5a754ae7f24"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user