Text Effects
Nine effects split SVG text into single glyphs, then swipe, drop, bounce, spin, flip, shuffle and zoom them.
What you are seeing
A dark panel headed text effects. Two short lines of handwritten text appear in the center, a new pair for each of nine effects. Letters fade in, change from yellow to red, fall from above, grow from the baseline, turn upright, flip, slide in from both sides or shrink into place. The effect name and a row of nine progress marks sit below the text.
How it works
A new script plays nine scenes, and each one passes two lines of new text to a different effect in the original CC0 engine.
The engine measures every character with getStartPositionOfChar, creates one text element per glyph at that position and hides the source line.
One animation per glyph changes opacity, color, offset or transform, and each starts slightly after the one before.
The script counts the end of every glyph animation, holds the finished line so it can be read, then fades it and starts the next scene.
History
Posted on September 25, 2010. The original page and sequence script carried a reserved-rights notice, so they are not republished. This version was written independently from a description of the demo and runs on the original CC0 engine, with new text and synthesized sound.
Source
/text-effects/text-effects.xhtml
<!-- Written for the SVG Wow! reconstruction. Independent of the original file at this path. -->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Text Effects | SVG Wow!</title>
<meta name="description" content="Nine animated text effects built on a per-glyph SVG engine, with new text and optional sound synthesized in the browser."/>
<link rel="icon" href="../res/2.0/images/favicon.svg" type="image/svg+xml"/>
<style type="text/css"><![CDATA[
:root { color-scheme: dark; --ink: #17161b; --paper: #f5efe3; --muted: #a29fac; --amber: #ffb454; --line: #3a3842; }
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; background: var(--ink); }
body { position: relative; overflow: hidden; color: var(--paper); font: 15px/1.3 system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif; }
#stage { display: block; width: 100%; height: 100%; }
#textGroup { font-family: "Segoe Print", "Bradley Hand", "Chalkboard SE", Noteworthy, "Comic Sans MS", cursive; font-size: 38px; fill: var(--paper); }
#info { font-size: 15px; letter-spacing: 0.14em; fill: var(--muted); text-anchor: middle; }
#effectName { font-size: 19px; fill: var(--amber); text-anchor: middle; }
#effectHint { font-size: 14px; fill: var(--muted); text-anchor: middle; }
.tick { fill: var(--line); transition: fill 0.25s linear; }
.tick.seen { fill: #76727f; }
.tick.now { fill: var(--amber); }
.controls { position: absolute; left: 50%; transform: translateX(-50%); display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; width: max-content; max-width: calc(100% - 16px); }
#launch, #endCard { top: 63%; }
#toolbar { bottom: 8px; }
[hidden] { display: none !important; }
button { min-height: 44px; padding: 9px 16px; font: 600 15px/1.2 system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif; color: var(--paper); background: #2a2831; border: 1px solid #55525e; border-radius: 6px; cursor: pointer; }
button.primary { color: #201503; background: var(--amber); border-color: var(--amber); }
button:hover { border-color: var(--paper); }
button:focus-visible { outline: 3px solid #fff; outline-offset: 2px; }
button:disabled { opacity: 0.6; cursor: default; }
#toolbar button { min-height: 40px; padding: 7px 12px; font-size: 14px; background: rgba(42, 40, 49, 0.92); }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
@media (max-width: 480px) { #launch, #endCard { top: auto; bottom: 16%; } button { padding: 9px 13px; } }
]]></style>
<script type="text/javascript" src="../res/3.0/scripts/compat/restore.js"></script>
<script type="text/javascript" src="../res/3.0/scripts/yui/yui/yui-debug.js"></script>
</head>
<body>
<h1 class="sr-only">Text Effects</h1>
<svg id="stage" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 480" preserveAspectRatio="xMidYMid meet" role="img" aria-label="A dark panel where short lines of text animate letter by letter.">
<desc>A dark panel with a heading at the top, two lines of handwritten text in the middle, the name of the current effect below them and a row of nine progress marks. Each effect moves the letters of a new line one at a time.</desc>
<defs>
<radialGradient id="glow" cx="50%" cy="46%" r="62%">
<stop offset="0" stop-color="#2a2733"/>
<stop offset="1" stop-color="#17161b"/>
</radialGradient>
</defs>
<rect x="-640" y="-480" width="1920" height="1440" fill="url(#glow)"/>
<text id="info" x="320" y="42">TEXT EFFECTS</text>
<g id="textGroup"></g>
<text id="effectName" x="320" y="358"></text>
<text id="effectHint" x="320" y="380"></text>
<g id="ticks"></g>
</svg>
<div id="launch" class="controls">
<button id="startButton" class="primary" type="button">Start</button>
<button id="startSoundButton" type="button">Start with sound</button>
</div>
<div id="endCard" class="controls" hidden="hidden">
<button id="replayButton" class="primary" type="button">Play again</button>
</div>
<div id="toolbar" class="controls" role="group" aria-label="Playback controls" hidden="hidden">
<button id="soundButton" type="button" aria-pressed="false">Sound off</button>
<button id="nextButton" type="button">Next effect</button>
<button id="stopButton" type="button">Stop</button>
</div>
<p id="live" class="sr-only" role="status" aria-live="polite"></p>
<script type="text/javascript" src="text-effects.js"></script>
</body>
</html>
/text-effects/text-effects.js
/* Written for the SVG Wow! reconstruction. Independent of the original file at this path. */
/*
* Plays nine scenes in turn. Each scene hands two new lines of text to one
* effect from the CC0 engine in res/3.0/scripts/tools/text-effects.js.
*/
(function () {
'use strict';
var SVG_NS = 'http://www.w3.org/2000/svg';
var CENTER_X = 320;
var LINE_Y = [196, 250];
var HOLD_MS = 1500;
var FADE_MS = 320;
var SCENE_LIMIT_MS = 11000;
var SCENES = [
{
effect: 'opacity-swipe', name: 'opacity swipe',
hint: 'Letters fade in from left to right.',
lines: ['Ink arrives quietly,', 'one letter at a time'],
config: {duration: 0.6, offset: 0.035},
ink: '#f5efe3', cue: {root: 50, steps: [0, 2, 4, 7, 9], gap: 0.16}
},
{
effect: 'color-swipe', name: 'color swipe',
hint: 'A band of color runs along the line.',
lines: ['A warm wave passes', 'and leaves red behind'],
config: {offset: 0.04, startColor: '#ffd166', endColor: '#ff5d73'},
ink: '#ff5d73', cue: {root: 53, steps: [0, 4, 2, 7, 4, 9], gap: 0.13}
},
{
effect: 'whip', name: 'whip',
hint: 'Letters drop from above and spring into place.',
lines: ['Dropped from the rafters,', 'caught on a spring'],
config: {fallHeight: -420},
ink: '#8fd3ff', cue: {root: 57, steps: [9, 7, 4, 2, 0], gap: 0.09}
},
{
effect: 'bouncing-letters', name: 'bouncing letters',
hint: 'Each letter grows up from its baseline.',
lines: ['Tall words stretch,', 'then land on their feet'],
config: {},
ink: '#b7f09a', cue: {root: 48, steps: [0, 7, 2, 9, 4, 7], gap: 0.17}
},
{
effect: 'wiggling', name: 'wiggling',
hint: 'Letters arrive upside down and wobble upright.',
lines: ['Upside down is fine', 'for a little while'],
config: {duration: 2.4, offset: 0.04},
ink: '#ffc98f', cue: {root: 55, steps: [0, 2, 0, 4, 2, 7], gap: 0.2}
},
{
effect: 'horizontal-flip', name: 'horizontal flip',
hint: 'Letters open around a horizontal axis.',
lines: ['Shutters open', 'along the whole street'],
config: {duration: 0.5, offset: 0.04},
ink: '#d6c2ff', cue: {root: 52, steps: [0, 4, 7, 9], gap: 0.12}
},
{
effect: 'vertical-flip', name: 'vertical flip',
hint: 'Letters turn around a vertical axis.',
lines: ['Cards turn over', 'to show their faces'],
config: {duration: 0.5, offset: 0.04},
ink: '#8ff0dc', cue: {root: 50, steps: [9, 4, 7, 2, 4, 0], gap: 0.12}
},
{
effect: 'horizontal-shuffle', name: 'horizontal shuffle',
hint: 'Odd and even letters slide in from opposite sides.',
lines: ['Two crowds cross', 'and find their seats'],
config: {duration: 1.4, offset: 0.02, shuffleWidth: 700},
ink: '#ffe08a', cue: {root: 57, steps: [0, 9, 2, 7, 4], gap: 0.1}
},
{
effect: 'zoom-out', name: 'zoom out',
hint: 'Large faint letters shrink into position.',
lines: ['Step back a little', 'and it all fits'],
config: {duration: 0.7, offset: 0.04},
ink: '#f5efe3', cue: {root: 45, steps: [0, 4, 7, 9, 12, 16], gap: 0.18}
}
];
var $ = function (id) { return document.getElementById(id); };
var ui = {
info: $('info'), name: $('effectName'), hint: $('effectHint'),
group: $('textGroup'), ticks: $('ticks'), live: $('live'),
launch: $('launch'), endCard: $('endCard'), toolbar: $('toolbar'),
start: $('startButton'), startSound: $('startSoundButton'),
replay: $('replayButton'), sound: $('soundButton'),
next: $('nextButton'), stop: $('stopButton')
};
var Y = null;
var state = 'loading';
var sceneIndex = -1;
// Raised whenever a scene is replaced, so late callbacks can see they are stale.
var sceneToken = 0;
var holder = null;
var running = null;
var timer = null;
function reducedMotion() {
return !!(window.matchMedia &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches);
}
// =========================================================================
// Sound: short mallet phrases, one per scene, made with Web Audio.
// The context is created only from a click or key press.
// =========================================================================
var sound = {ctx: null, out: null, enabled: false, unavailable: false};
// Whether Play again should bring the sound back.
var wantSound = false;
function ensureAudio() {
if (sound.ctx) { return true; }
var Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx) { return false; }
try {
var ctx = new Ctx(), out = ctx.createGain(), tone = ctx.createBiquadFilter(),
echo = ctx.createDelay(1), feedback = ctx.createGain(), wet = ctx.createGain();
out.gain.value = 0;
tone.type = 'lowpass';
tone.frequency.value = 2600;
echo.delayTime.value = 0.27;
feedback.gain.value = 0.28;
wet.gain.value = 0.3;
out.connect(tone);
tone.connect(ctx.destination);
tone.connect(echo);
echo.connect(feedback);
feedback.connect(echo);
echo.connect(wet);
wet.connect(ctx.destination);
sound.ctx = ctx;
sound.out = out;
return true;
} catch (e) {
return false;
}
}
function renderSoundButton() {
ui.sound.textContent = sound.unavailable ? 'Sound unavailable' :
(sound.enabled ? 'Sound on' : 'Sound off');
ui.sound.setAttribute('aria-pressed', sound.enabled ? 'true' : 'false');
ui.sound.disabled = sound.unavailable;
}
function setSound(on) {
if (on && !ensureAudio()) {
sound.unavailable = true;
sound.enabled = false;
renderSoundButton();
return;
}
sound.enabled = on;
if (sound.ctx) {
var now = sound.ctx.currentTime;
if (on && sound.ctx.state === 'suspended') { sound.ctx.resume(); }
sound.out.gain.cancelScheduledValues(now);
sound.out.gain.setValueAtTime(sound.out.gain.value, now);
sound.out.gain.linearRampToValueAtTime(on ? 0.55 : 0, now + 0.08);
}
renderSoundButton();
}
function mallet(midi, when, length, level) {
var ctx = sound.ctx, freq = 440 * Math.pow(2, (midi - 69) / 12),
body = ctx.createOscillator(), shimmer = ctx.createOscillator(),
env = ctx.createGain(), shimmerLevel = ctx.createGain();
body.type = 'triangle';
body.frequency.value = freq;
shimmer.type = 'sine';
shimmer.frequency.value = freq * 3.01;
shimmerLevel.gain.value = 0.16;
env.gain.setValueAtTime(0.0001, when);
env.gain.exponentialRampToValueAtTime(level, when + 0.012);
env.gain.exponentialRampToValueAtTime(0.0001, when + length);
body.connect(env);
shimmer.connect(shimmerLevel);
shimmerLevel.connect(env);
env.connect(sound.out);
body.start(when);
shimmer.start(when);
body.stop(when + length + 0.02);
shimmer.stop(when + length + 0.02);
}
function playCue(cue) {
if (!sound.enabled || !sound.ctx) { return; }
var t = sound.ctx.currentTime + 0.04;
mallet(cue.root - 12, t, 1.5, 0.2);
cue.steps.forEach(function (step, i) {
mallet(cue.root + 12 + step, t + i * cue.gap, 0.75, 0.15);
});
}
// =========================================================================
// Drawing
// =========================================================================
function clearTimer() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
function buildTicks() {
SCENES.forEach(function (scene, i) {
var r = document.createElementNS(SVG_NS, 'rect');
r.setAttribute('class', 'tick');
r.setAttribute('x', CENTER_X - 104 + i * 24);
r.setAttribute('y', 400);
r.setAttribute('width', 16);
r.setAttribute('height', 3);
r.setAttribute('rx', 1.5);
ui.ticks.appendChild(r);
});
}
function markTicks(current) {
var marks = ui.ticks.childNodes;
for (var i = 0; i < marks.length; i++) {
marks[i].setAttribute('class', 'tick' +
(i === current ? ' now' : (i < current ? ' seen' : '')));
}
}
function retireHolder() {
var old = holder;
holder = null;
if (!old) { return; }
old.style.transition = 'opacity ' + FADE_MS + 'ms linear';
old.style.opacity = '0';
setTimeout(function () {
if (old.parentNode) { old.parentNode.removeChild(old); }
}, FADE_MS + 40);
}
/** Creates the centered source lines. The engine needs start-anchored text. */
function drawLines(lines, ink) {
var g = document.createElementNS(SVG_NS, 'g'), texts = [];
g.setAttribute('fill', ink);
ui.group.appendChild(g);
lines.forEach(function (line, i) {
var t = document.createElementNS(SVG_NS, 'text');
t.textContent = line;
t.setAttribute('x', 0);
t.setAttribute('y', LINE_Y[i]);
g.appendChild(t);
t.setAttribute('x', Math.round(CENTER_X - t.getComputedTextLength() / 2));
texts.push(t);
});
holder = g;
return texts;
}
function halt() {
sceneToken++;
clearTimer();
if (running) {
running.anims.forEach(function (a) { a.stop(); });
running = null;
}
}
// =========================================================================
// Sequence
// =========================================================================
function showScene(i) {
halt();
retireHolder();
sceneIndex = i;
var scene = SCENES[i], token = sceneToken, calm = reducedMotion();
ui.info.textContent = 'EFFECT ' + (i + 1) + ' OF ' + SCENES.length;
ui.name.textContent = scene.name;
ui.hint.textContent = calm ? scene.hint : '';
ui.live.textContent = scene.name + ': ' + scene.lines.join(' ');
markTicks(i);
playCue(scene.cue);
var lines = drawLines(scene.lines, scene.ink);
// With reduced motion the line stays still and Next effect moves on.
if (calm) { return; }
var nodes = lines.map(function (t) { return Y.one(t); }),
effect = window.sw.TextEffects.effects[scene.effect].applyEffect(nodes, scene.config),
waiting = effect.anims.length;
function settle() {
if (token !== sceneToken) { return; }
clearTimer();
running = null;
timer = setTimeout(advance, HOLD_MS);
}
effect.anims.forEach(function (anim) {
anim.onEnd(function () {
waiting--;
if (waiting === 0) { settle(); }
});
});
effect.setStartState();
running = effect;
timer = setTimeout(settle, SCENE_LIMIT_MS);
effect.run();
}
function advance() {
if (state !== 'playing') { return; }
if (sceneIndex + 1 < SCENES.length) {
showScene(sceneIndex + 1);
} else {
finish();
}
}
function begin(withSound) {
if (state === 'loading' || state === 'playing') { return; }
state = 'playing';
wantSound = !!withSound;
setSound(wantSound);
ui.launch.hidden = true;
ui.endCard.hidden = true;
ui.toolbar.hidden = false;
ui.next.focus();
showScene(0);
}
function finish() {
halt();
retireHolder();
state = 'finished';
setSound(false);
sceneIndex = -1;
markTicks(SCENES.length);
ui.info.textContent = 'TEXT EFFECTS';
ui.name.textContent = 'all nine effects';
ui.hint.textContent = '';
drawLines(['Nine ways to move', 'a single line'], '#f5efe3');
ui.live.textContent = 'Sequence finished. Play again is available.';
ui.toolbar.hidden = true;
ui.endCard.hidden = false;
ui.replay.focus();
}
// =========================================================================
// Controls
// =========================================================================
function bindControls() {
ui.start.addEventListener('click', function () { begin(false); });
ui.startSound.addEventListener('click', function () { begin(true); });
ui.replay.addEventListener('click', function () { begin(wantSound); });
ui.sound.addEventListener('click', function () {
setSound(!sound.enabled);
wantSound = sound.enabled;
});
ui.next.addEventListener('click', advance);
ui.stop.addEventListener('click', finish);
document.addEventListener('keydown', function (evt) {
if (evt.altKey || evt.ctrlKey || evt.metaKey) { return; }
var key = evt.key, onButton = evt.target && evt.target.localName === 'button';
if (state === 'playing') {
if (key === 'ArrowRight' || key === 'n') {
advance();
} else if (key === 'Escape') {
finish();
} else if (key === 'm') {
ui.sound.click();
} else {
return;
}
} else if ((key === 'Enter' || key === ' ') && !onButton) {
begin(state === 'finished' && wantSound);
} else if (key === 's') {
begin(true);
} else {
return;
}
evt.preventDefault();
});
}
function ready(instance) {
Y = instance;
state = 'idle';
buildTicks();
drawLines(['Nine ways to move', 'a single line'], '#f5efe3');
ui.hint.textContent = reducedMotion() ?
'Reduced motion is on, so each effect is shown at rest.' : '';
bindControls();
renderSoundButton();
try { ui.start.focus({preventScroll: true}); } catch (e) { ui.start.focus(); }
}
window.YUI({
groups: {
svg: {
combine: false,
base: '../res/3.0/scripts/yui/',
modules: {
'node-svg': {path: 'svg/node-svg-debug.js', requires: ['node']},
'dom-style-svg': {path: 'svg/dom-style-svg-debug.js', requires: ['node', 'dom-svg']},
'dom-svg': {path: 'svg/dom-svg-debug.js', requires: ['dom']},
'anim-timing': {path: 'anim-timing/anim-timing-debug.js', requires: ['anim', 'node-svg']},
'anim-svg': {path: 'svg/anim-svg-debug.js', requires: ['anim', 'dom-style-svg']},
'text-effects': {path: '../tools/text-effects.js', requires: ['anim-svg', 'anim-timing']}
}
}
}
}).use('text-effects', ready);
})();
/res/3.0/scripts/tools/text-effects.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
(function () {
YUI.add("text-effects",
function (Y) {
var sw = window.sw, Animate = sw.animation.Animate,
Easing = Y.Easing,
effectsLib = {};
sw.TextEffects = {
effects: effectsLib
};
/**
* This class represents a series of animations and actions which can be
* manipulated as a single entity.
*
* @param anims the set of animations composing this effect
*/
function Effect (anims) {
this.anims = anims;
}
Effect.prototype.run = function () {
this.anims[0].run.apply(this.anims[0], arguments);
};
Effect.prototype.onBegin = function () {
this.anims[0].onBegin.apply(this.anims[0], arguments);
};
Effect.prototype.onEnd = function () {
var i = this.anims.length - 1;
this.anims[i].onBegin.apply(this.anims[i], arguments);
};
Effect.prototype.setStartState = function () {
var anims = this.anims, n = anims.length;
for (var i = 0; i < n; i++) {
anims[i].applyStartFrame();
}
};
/**
* Utility method: computes the advance for each character in a
* text string.
*/
function computeTextPositions (text) {
var tc = text.get('textContent'), n = tc.length, i, pos = [],
curPos = null, p, x, y, p0, dx = 0, dy = 0;
// This method uses getStartPositionOfChar. Safari, Opera, FireFox
// do different adjustments on the returned position. To compensate for
// the differences, the following code gets the text's x and y
// coordinates and adds the delta between these values and the
// value getStartPositionOfChar returns for the first character.
x = text.get('x');
y = text.get('y');
text.set('x', 0);
text.set('y', 0);
dx = x;
dy = y;
for (i = 0; i < n; i++) {
p = text._node.getStartPositionOfChar(i);
if (curPos === null ||
p.x !== curPos.p.x || p.y !== curPos.p.y) {
curPos = {
p: {x: p.x + dx, y: p.y + dy},
n: 1
};
pos.push(curPos);
} else {
// Same position, just increase the text run length
curPos.n++;
}
}
text.set('x', x);
text.set('y', y);
return pos;
}
var excludeAttrs = {
id: true,
x: true,
y: true,
dx: true,
dy: true,
'data-text-effect': true
}
/**
* Implementation helper: returns a handle that will set the desired style
* property on the target element.
*
* @param target the element target
* @param property the property to set
* @param val the property value
*/
function getStyleSetter (target, property, value) {
return function () {
target.setStyle(property, value);
}
}
/**
* Implementation helper, used to do nothing on setStartState.
*
*/
function noOp () {
}
/**
* Implementation helper. Merges the two configuration objects.
*
* @param target the default configuration object on which to merge the
* properties. Typically the defaults.
* @param config the user configuration
* @return the merged configuration, with the user defined properties or the
* defaults for unspecified properties.
*/
function mergeConfig (target, config) {
for (var q in config) {
if (config.hasOwnProperty(q)) {
target[q] = config[q];
}
}
return target;
}
/**
* Common utility method for text effects: breaks down the text into individual
* text element, one for each glyph.
*
* @param lines the text element(s) to break down.
* @return an array of text element spans
*/
function toGlyphSpans (lines) {
var spans = [];
Y.each(lines, function (text) {
var tc = text.get('textContent'), s,
ns = text.get('namespaceURI'),
pos = computeTextPositions(text), n = pos.length, p, j = 0,
tg = Y.one(document.createElementNS(ns, 'g')), attrs, item, val;
text.get('parentNode').appendChild(tg);
// Copy all the text element attributes onto the text group
attrs = text._node.attributes;
for (j = 0; j < attrs.length; j++) {
item = attrs.item(j);
val = item.nodeValue;
if (excludeAttrs[item.name] === undefined) {
if (item.name === "class") {
val = val.replace('text-effects', '');
}
if (val.length > 0) {
tg._node.setAttributeNS(item.namespaceURI,
item.name,
val);
}
}
}
tg.removeClass('text-effects');
j = 0;
for (var i = 0; i < n; i++) {
p = pos[i];
s = Y.one(document.createElementNS(ns, 'text'));
s.set('textContent', tc.substring(j, j + p.n));
s.set('x', p.p.x);
s.set('y', p.p.y);
tg.appendChild(s);
spans.push(s);
j += p.n;
}
text.setStyle('display', 'none');
});
return spans;
}
effectsLib['opacity-swipe'] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s, a, anims = [],
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
a = new Animate({
node: s,
from: {'fill-opacity': 0},
to: {'fill-opacity': 1},
duration: config.duration,
easing: config.easing
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], i * config.offset);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each letter
*/
duration: 0.25,
/**
* Offset between the start of each animation
*/
offset: 0.0125,
/**
* Easing method for the letter animationss
*/
easing: Easing.easeIn
};
}
};
effectsLib['color-swipe'] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s, a, anims = [],
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
a = new Animate({
node: s,
from: {'fill': config.startColor, 'fill-opacity': 0},
to: {'fill': config.endColor, 'fill-opacity': 1},
duration: 1,
easing: config.easing
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], i * config.offset);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each letter
*/
duration: 0.25,
/**
* Offset between the start of each animation
*/
offset: 0.03,
/**
* Start color
*/
startColor: 'orange',
/**
* End color
*/
endColor: 'crimson',
/**
* Easing method for the letter animationss
*/
easing: Easing.easeIn
};
}
};
effectsLib.whip = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s,
a, anims = [], o, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
o = config.fallHeight;
a = new Animate({
node: s,
from: {dy: o},
to: {dy: 0},
duration: config.duration,
easing: config.easing
});
s.setStyle('fill-opacity', 1);
s.set('dy', o);
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], i * 0.012);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each letter
*/
duration: 1.2,
/**
* Offset between the start of each animation
*/
offset: 0.012,
/**
* Height of the letter fall
* (may be negative)
*/
fallHeight: -500,
/**
* Easing method for the letter animationss
*/
easing: Easing.elasticOut
};
}
};
effectsLib['bouncing-letters'] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text),
n = spans.length, s, a, anims = [], x, y, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
y = s.get('y');
x = s.get('x');
a = new Animate({
node: s,
from: {transform: {sy: 0}},
to: {transform: {sy: 1}},
transformTemplate: "translate(" + x + "," + y + ")" +
"scale(1,#sy)" +
"translate(" + (-x) + "," + (-y) + ")",
duration: config.duration,
easing: config.easing
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], config.offset * i);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each bounce
*/
duration: 1.2,
/**
* Offset between the start of each letter animation
*/
offset: 0.05,
/**
* Easing method for the flips
*/
easing: Easing.elasticOut
};
}
};
effectsLib.wiggling = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s, a, anims = [],
bbox, cx, cy, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
bbox = s._node.getBBox();
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
a = new Animate({
node: s,
from: {transform: {r: 180}},
to: {transform: {r: 0}},
transformTemplate: "translate(" + cx + "," + cy + ")" +
"rotate(#r)" +
"translate(" + (-cx) + "," + (-cy) + ")",
duration: config.duration,
easing: Easing.elasticOut
});
anims.push(a);
a.onBegin(getStyleSetter(s, 'display', 'inline'));
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], config.offset * i);
}
textEffect = new Effect(anims);
textEffect.setStartState = function () {
for (var i = 0; i < n; i++) {
anims[i].applyStartFrame();
spans[i].setStyle('display', 'none');
}
};
return textEffect;
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each of the flips
*/
duration: 3,
/**
* Offset between the start of each letter flip
*/
offset: 0.05,
/**
* Easing method for the flips
*/
easing: Easing.elasticOut
};
}
};
effectsLib["horizontal-flip"] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s, a, anims = [],
bbox, cx, cy, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
bbox = s._node.getBBox();
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
a = new Animate({
node: s,
from: {transform: {sy: 0}},
to: {transform: {sy: 1}},
transformTemplate: "translate(" + cx + "," + cy + ")" +
"scale(1, #sy)" +
"translate(" + (-cx) + "," + (-cy) + ")",
duration: config.duration,
easing: config.easing
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], config.offset * i);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each of the flips
*/
duration: 0.25,
/**
* Offset between the start of each letter flip
*/
offset: 0.03,
/**
* Easing method for the flips
*/
easing: Easing.easeIn
};
}
};
effectsLib["vertical-flip"] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s, a, anims = [],
bbox, cx, cy, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
bbox = s._node.getBBox();
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
a = new Animate({
node: s,
from: {transform: {sx: 0}},
to: {transform: {sx: 1}},
transformTemplate: "translate(" + cx + "," + cy + ")" +
"scale(#sx, 1)" +
"translate(" + (-cx) + "," + (-cy) + ")",
duration: config.duration,
easing: config.easing
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], config.offset * i);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each of the flips
*/
duration: 0.25,
/**
* Offset between the start of each letter flip
*/
offset: 0.03,
/**
* Easing method for the flips
*/
easing: Easing.easeIn
};
}
};
effectsLib['horizontal-shuffle'] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s,
a, anims = [], o, dir, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
o = config.shuffleWidth;
dir = i % 2 === 0 ? 1 : -1;
a = new Animate({
node: s,
from: {dx: dir * o, 'fill-opacity': 0},
to: {dx: 0, 'fill-opacity': 1},
duration: 0.5 * (1 + Math.random()) * config.duration,
easing: config.easing
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], i * config.offset);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each letter
*/
duration: 1,
/**
* Offset between the start of each animation
*/
offset: 0.012,
/**
* Max width for the shuffle
*/
shuffleWidth: 1000,
/**
* Easing method for the letter animationss
*/
easing: Easing.easeOutStrong
};
}
};
effectsLib['zoom-out'] = {
/**
* Applies the effect to the given text element.
*/
applyEffect : function (text, cfg) {
var spans = toGlyphSpans(text), n = spans.length, s,
a, anims = [], bbox, cx, cy, textEffect,
config = mergeConfig(this.getConfig(), cfg);
for (var i = 0; i < n; i++) {
s = spans[i];
bbox = s._node.getBBox();
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2;
a = new Animate({
node: s,
from: {transform: {sx: 3, sy: 3}, 'fill-opacity': 0},
to: {transform: {sx: 1, sy: 1}, 'fill-opacity': 1},
duration: 0.5 * (1 + Math.random()) * config.duration,
easing: config.easing,
transformTemplate: "translate(" + cx + "," + cy + ")" +
"scale(#sx, #sy)" +
"translate(" + (-cx) + "," + (-cy) + ")",
transformTemplate2: "scale(#sx, #sy)"
});
anims.push(a);
}
for (i = 1; i < n; i++) {
anims[0].onBegin(anims[i], i * config.offset);
}
return new Effect(anims);
},
/**
* Configuration
*/
getConfig: function () {
return {
/**
* Duration for each letter
*/
duration: 0.25,
/**
* Offset between the start of each animation
*/
offset: 0.05,
/**
* Max width for the shuffle
*/
shuffleWidth: 1000,
/**
* Easing method for the letter animationss
*/
easing: Easing.none
};
}
};
});
})();
/res/3.0/scripts/compat/restore.js
/**
* Compatibility layer for the restored YUI 3 demos.
*
* Load this before yui-debug.js. It keeps the YUI loader on this origin,
* restores two SVG DOM members that browsers have removed, and provides the
* start control and the synthesized sound used in place of the original
* music tracks. Sound is created only after a click on a start button.
*/
(function () {
'use strict';
// Never let the loader build a combo URL for the retired YUI CDN.
window.YUI_config = window.YUI_config || {};
window.YUI_config.combine = false;
// Only the -debug builds of the modules were archived.
window.YUI_config.filter = 'debug';
window.YUI_config.debug = false;
window.YUI_config.useBrowserConsole = false;
// =========================================================================
// Removed SVG DOM members
// =========================================================================
var graphics = (window.SVGGraphicsElement || window.SVGElement).prototype;
if (!graphics.getTransformToElement) {
graphics.getTransformToElement = function (target) {
return target.getScreenCTM().inverse().multiply(this.getScreenCTM());
};
}
if (!('nearestViewportElement' in graphics)) {
Object.defineProperty(graphics, 'nearestViewportElement', {
configurable: true,
get: function () { return this.ownerSVGElement; }
});
}
// dom-utils.js only installs this when it is missing. Its own version
// passes an output argument to transformPoint, which DOMMatrix ignores.
graphics.getViewportBBox = function () {
var box = this.getBBox(),
m = this.getTransformToElement(this.nearestViewportElement),
xs = [], ys = [];
[[box.x, box.y], [box.x + box.width, box.y],
[box.x, box.y + box.height], [box.x + box.width, box.y + box.height]
].forEach(function (p) {
xs.push(m.a * p[0] + m.c * p[1] + m.e);
ys.push(m.b * p[0] + m.d * p[1] + m.f);
});
var minX = Math.min.apply(null, xs), minY = Math.min.apply(null, ys);
return {
x: minX,
y: minY,
width: Math.max.apply(null, xs) - minX,
height: Math.max.apply(null, ys) - minY
};
};
// =========================================================================
// Start control, sound toggle and replay button
// =========================================================================
var css = [
'.sw-controls{position:absolute;z-index:20;display:flex;flex-wrap:wrap;gap:8px;',
'justify-content:center;transform:translate(-50%,-50%);width:max-content;max-width:92vw}',
'.sw-controls button,.sw-sound{font:600 15px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;',
'min-height:44px;padding:10px 18px;border-radius:6px;border:1px solid #202020;',
'background:#202020;color:#fff;cursor:pointer}',
'.sw-controls button.sw-alt{background:#fff;color:#202020}',
'.sw-controls button:hover,.sw-sound:hover{background:#b0122f;border-color:#b0122f;color:#fff}',
'.sw-controls button:focus-visible,.sw-sound:focus-visible{outline:3px solid #ffb000;outline-offset:2px}',
'.sw-sound{position:fixed;top:8px;right:8px;z-index:21;font-size:13px;min-height:36px;padding:6px 12px}'
].join('');
function addStyle() {
if (document.getElementById('sw-restore-style')) { return; }
var style = document.createElement('style');
style.id = 'sw-restore-style';
style.textContent = css;
(document.head || document.documentElement).appendChild(style);
}
function button(label, className, handler) {
var b = document.createElement('button');
b.setAttribute('type', 'button');
if (className) { b.className = className; }
b.textContent = label;
b.addEventListener('click', function (event) {
event.stopPropagation();
handler(event);
});
return b;
}
function placeOver(box, target, at) {
function place() {
var r = target.getBoundingClientRect();
box.style.left = (r.left + window.pageXOffset + r.width / 2) + 'px';
box.style.top = (r.top + window.pageYOffset + r.height * at) + 'px';
}
place();
window.addEventListener('resize', place);
return function () { window.removeEventListener('resize', place); };
}
/**
* Shows "Start" and "Start with sound" over the target element.
*
* @param opts.target the element to centre the buttons on
* @param opts.onStart called once with true when sound was requested
* @param opts.score optional note pattern for the synthesized sound
* @param opts.at vertical position over the target, 0 to 1
*/
function startControl(opts) {
addStyle();
var box = document.createElement('div'), release, primary;
box.className = 'sw-controls';
function go(withSound) {
release();
box.parentNode.removeChild(box);
if (withSound) {
var s = createScore(opts.score);
s.play();
soundToggle(s);
}
opts.onStart(withSound);
}
primary = button('Start', '', function () { go(false); });
box.appendChild(primary);
box.appendChild(button('Start with sound', 'sw-alt', function () { go(true); }));
document.body.appendChild(box);
release = placeOver(box, opts.target, opts.at === undefined ? 0.5 : opts.at);
try { primary.focus({preventScroll: true}); } catch (e) { primary.focus(); }
}
function soundToggle(score) {
var b = button('Sound off', 'sw-sound', function () {
if (score.playing()) {
score.stop();
b.textContent = 'Sound on';
} else {
score.play();
b.textContent = 'Sound off';
}
});
document.body.appendChild(b);
}
/** Shows a "Play again" button, which reloads the document. */
function replay(target, at) {
addStyle();
var box = document.createElement('div');
box.className = 'sw-controls';
box.appendChild(button('Play again', '', function () { window.location.reload(); }));
document.body.appendChild(box);
placeOver(box, target, at === undefined ? 0.92 : at);
}
// =========================================================================
// Synthesized sound: a soft plucked pattern scheduled with Web Audio.
// =========================================================================
var DEFAULT_SCORE = {
tempo: 92,
notes: [220, 0, 261.63, 293.66, 0, 329.63, 293.66, 0,
196, 0, 246.94, 293.66, 0, 329.63, 392, 0],
bass: [110, 110, 98, 98]
};
function createScore(pattern) {
var score = pattern || DEFAULT_SCORE,
stepLength = 60 / score.tempo / 2,
ctx = null, master = null, timer = null, step = 0, nextTime = 0;
function pluck(freq, when, length, level, type) {
var osc = ctx.createOscillator(), gain = ctx.createGain();
osc.type = type;
osc.frequency.value = freq;
gain.gain.setValueAtTime(0.0001, when);
gain.gain.exponentialRampToValueAtTime(level, when + 0.015);
gain.gain.exponentialRampToValueAtTime(0.0001, when + length);
osc.connect(gain);
gain.connect(master);
osc.start(when);
osc.stop(when + length + 0.02);
}
function schedule() {
while (nextTime < ctx.currentTime + 0.25) {
var n = score.notes[step % score.notes.length];
if (n) { pluck(n, nextTime, 0.7, 0.16, 'triangle'); }
if (step % 4 === 0) {
pluck(score.bass[(step / 4) % score.bass.length], nextTime,
stepLength * 3.5, 0.2, 'sine');
}
step++;
nextTime += stepLength;
}
}
return {
play: function () {
var Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx || timer !== null) { return; }
if (!ctx) {
ctx = new Ctx();
master = ctx.createGain();
master.gain.value = 0.5;
master.connect(ctx.destination);
}
ctx.resume();
nextTime = ctx.currentTime + 0.05;
schedule();
timer = setInterval(schedule, 80);
},
stop: function () {
if (timer !== null) { clearInterval(timer); timer = null; }
if (ctx) { ctx.suspend(); }
},
playing: function () { return timer !== null; }
};
}
window.SwRestore = {
startControl: startControl,
replay: replay,
createScore: createScore,
reducedMotion: function () {
return !!(window.matchMedia &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches);
}
};
})();
/res/3.0/scripts/yui/anim-timing/anim-timing-debug.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
(function () {
window.sw = window.sw || {};
sw.animation = sw.animation || {};
YUI.add("anim-timing", function (Y) {
// =============================================================================
// Utility class used to manage animation time offsets.
// =============================================================================
var OffsetManager = {
/**
* List of pending offsets
*/
_pendingOffsets: [],
/**
* The most recent timer identifier (used for cancellation
*/
_lastTimerId: -1,
/**
* Adds a new offset client.
*
* @param p_offset {Number} the offset after which callback should be called.
* @param p_callback the callback to invoke after offset expires. Should
* be a function or an animation instance (i.e., an object with a
* 'run' method).
*/
addOffsetListener : function (p_offset, p_callback) {
p_offset = p_offset !== undefined ? p_offset : 0;
if (p_offset === undefined || p_offset <= 0) {
// Invoke callback immediately.
this._invokeCallback(p_callback);
} else {
var currentTime = (new Date()).getTime(),
offset = {
callback: p_callback,
offset: p_offset,
requestedAt: currentTime,
remainingOffset: p_offset * 1000
};
this._updatePendingOffsets(currentTime);
if (this._insertPendingOffset(offset) === 0) {
// the new offset is at index 0, i.e., it is our most immediate
// new timer. Cancel the current timer if one was set.
// In all cases, start a new timeout.
if (this._lastTimerId !== -1) {
clearTimeout(this._lastTimerId);
}
this._startTimer();
}
}
},
/**
* Implementation helper.
* Starts the timer on the most immediate callback. This assumes the
* callbacks have been sorted in time order and that there is at least
* one.
*/
_startTimer : function () {
this._lastTimerId = setTimeout(function () {
OffsetManager._onTimeout();
}, this._pendingOffsets[0].remainingOffset);
},
/**
* setTimeout callback
*
*/
_onTimeout : function () {
this._timerId = -1;
var po = this._pendingOffsets, o,
currentTime = (new Date()).getTime();
this._updatePendingOffsets(currentTime);
o = po[0];
while (o !== undefined && o.remainingOffset <= 0) {
po.splice(0, 1);
this._invokeCallback(o.callback);
o = po[0];
}
if (po.length > 0) {
this._startTimer();
}
},
/**
* Implementation helper.
*
* Updates the remainingOffset on the _pendingOffsets elements.
*
* @param p_currentTime the current time when this call is made
*/
_updatePendingOffsets : function (p_currentTime) {
var po = this._pendingOffsets, o;
var n = po.length;
for (var i = 0; i < n; i++) {
o = po[i];
o.remainingOffset = o.offset * 1000 - (p_currentTime - o.requestedAt);
}
},
/**
* Implementation helper.
*
* Inserts a new timing offset in the array managed by the offset manager.
*
* @param p_offset the new offset object to insert.
* @return the index at which the new offset object was inserted.
*/
_insertPendingOffset : function (p_offset) {
var po = this._pendingOffsets, o;
var n = po.length;
for (var i = 0; i < n; i++) {
o = po[i];
if (o.remainingOffset > p_offset.remainingOffset) {
po.splice(i, 0, p_offset);
break;
}
}
if (i === n) {
po.push(p_offset);
}
return i;
},
/**
* Invokes the callback.
*
* @param p_callback may be a function or an animation instance.
*/
_invokeCallback : function (p_callback) {
if (typeof p_callback === "function") {
p_callback.call();
} else if (typeof p_callback === "object" &&
p_callback !== null &&
typeof p_callback.run === "function") {
p_callback.run();
}
}
};
/**
* Simple extension of the YUI animation classes to handle SVG transforms.
*
* The extension handles the "r", "sx", "sy", "tx" and "ty" pseudo attributes
* by manipulating the transform of the target element using a template.
*
* @param config the configuration
*
* @see http://developer.yahoo.com/yui/docs/YAHOO.util.Anim.html
*/
sw.animation.Animate = function (config) {
sw.animation.Animate.superclass.constructor.apply(this, arguments);
};
sw.animation.Animate.NAME = "sw.animation.Animate";
sw.animation.Animate.ATTRS = {
transformTemplate: {
value: "rotate(#r) scale(#sx, #sy) translate(#tx, #ty)"
}
};
/**
* Work around usage of regexp in YUI to detect which properties should have a
* default unit.
*
* Unfortunately, the default regexp matches stop-opacity with 'top'
*/
Y.Anim.RE_DEFAULT_UNIT = /^width|^height|^top|^right|^bottom|^left|^margin.*|^padding.*|^border.*$/i;
Y.extend(sw.animation.Animate, Y.Anim, {
/**
* Initializer.
* @see Y.Base
*/
initializer : function () {
var _endCallbacks = [],
_beginCallbacks = [];
this._endCallbacks = _endCallbacks;
this._beginCallbacks = _beginCallbacks;
this.on("end", function () {
for (var i = 0; i < _endCallbacks.length; i++) {
OffsetManager.addOffsetListener(_endCallbacks[i].offset,
_endCallbacks[i].callback);
}
});
this.on("start", function () {
for (var i = 0; i < _beginCallbacks.length; i++) {
OffsetManager.addOffsetListener(_beginCallbacks[i].offset,
_beginCallbacks[i].callback);
}
});
// Override the run/stop methods. Since it is initialized in the animate
// class' constructor, we need to do an override in the derived class'
// constructor as well.
this._superRun = sw.animation.Animate.superclass.run;
this._superStop = sw.animation.Animate.superclass.stop;
},
/**
* Override the base class' _runAttrs to fix a bug in reverse mode.
*/
_runAttrs: function(t, d, reverse) {
var attr = this._runtimeAttr,
customAttr = Y.Anim.behaviors,
easing = attr.easing,
lastFrame = d,
attribute,
setter,
i;
if (reverse) {
t = d - t;
lastFrame = 0;
}
for (i in attr) {
if (attr[i].to) {
attribute = attr[i];
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Y.Anim.DEFAULT_SETTER;
if (t < d && t > 0) {
setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);
} else {
setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit);
}
}
}
},
/**
* Applies the initial animation value.
*/
applyStartFrame: function() {
this._checkRuntimeAttr();
var d = this._runtimeAttr.duration,
t = 0,
attr = this._runtimeAttr,
customAttr = Y.Anim.behaviors,
easing = attr.easing,
attribute,
setter,
i,
reverse = this.get("reverse");
if (reverse) {
t = d;
}
for (i in attr) {
if (attr[i].to) {
attribute = attr[i];
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Y.Anim.DEFAULT_SETTER;
setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);
}
}
},
/**
* Implementation helper: checks that the runtime attributes have been
* initialized. If not, initialize them now.
*/
_checkRuntimeAttr : function () {
if (this._runtimeAttr === undefined) {
this._initAnimAttr();
}
},
/**
* Returns a handler that will run this animation instance when invoked.
*/
getRunHandler : function () {
var that = this;
if (this._runHandler === undefined) {
this._runHandler = function () {
that.run();
};
}
return this._runHandler;
},
/**
* Returns the handler that will stop this animation instance when invoked
*/
getStopHandler : function () {
var that = this;
if (this._stopHandler === undefined) {
this._stopHandler = function () {
that.stop();
};
}
return this._stopHandler;
},
/**
* Adds a function of animation to call or play when this animation ends
*
* @param p_animOrCallback an animation or function to trigger when this
* animation ends
* @param p_oOffset {Number} optional time offset to add before calling the
* end callback.
*/
onEnd : function (p_animOrCallback, p_oOffset) {
this._endCallbacks.push({
callback: p_animOrCallback,
offset: p_oOffset
});
},
/**
* Adds a function of animation to call or play when this animation begins
*
* @param p_animOrCallback an animation or function to trigger when this
* animation begins
* @param p_oOffset {Number} optional time offset to add before calling the
* begin callback.
*/
onBegin : function (p_animOrCallback, p_oOffset) {
this._beginCallbacks.push({
callback: p_animOrCallback,
offset: p_oOffset
});
},
/**
* Starts the animation with the requseted offset. The offset is optional,
* and defaults to zero if unspecified.
*
* @param p_oOffset {Number} optional time offset, in seconds, before
* starting the animation.
*/
run : function (p_offset) {
if (p_offset === undefined || p_offset === 0) {
this._superRun.call(this);
this.applyStartFrame(); // Applies the initial animation frame.
} else {
OffsetManager.addOffsetListener(p_offset, this);
}
},
/**
* Stops the animation with the requested offset. The offset is optional and
* defaults to zero if unspecified.
*
* @param p_oOffset {Number} optional time offset, in seconds, before ending
* the animation.
*/
stop : function (p_offset) {
if (p_offset === undefined || p_offset === 0) {
this._superStop.call(this);
} else {
OffsetManager.addOffsetListener(p_offset, this.getStopHandler());
}
},
/**
* Adds a start condition for this animation.
*
* @param p_evtTarget the event target (DOM object) or animation.
* @param p_evtType the event type. If the target is an animation instance,
* should be "begin" or "end".
* @param p_oOffset an offset after which the animation should begin. In
* seconds.
*/
beginOn : function (p_evtTarget, p_evtType, p_oOffset) {
var that = this;
if (p_evtTarget.run !== undefined) {
if (p_evtType === "begin") {
p_evtTarget.onBegin(this, p_oOffset);
} else if (p_evtType === "end") {
p_evtTarget.onEnd(this, p_oOffset);
}
} else {
p_evtTarget.on(p_evtType, function () {
that.run(p_oOffset);
});
}
},
/**
* Adds an end condition for this animation.
*
* @param p_evtTarget the event target
* @param p_evtType the event type. If the target is an animation instance,
* should be "begin" or "end".
* @param p_oOffset an offset after which the animation should begin In
* seconds.
*/
endOn : function (p_evtTarget, p_evtType, p_oOffset) {
var that = this;
if (p_evtTarget.run !== undefined) {
if (p_evtType === "begin") {
p_evtTarget.onBegin(function () {
that.stop(false);
}, p_oOffset);
} else if (p_evtType === "end") {
p_evtTarget.onEnd(function() {
that.stop(false);
}, p_oOffset);
}
} else {
p_evtTarget.on(p_evtType, function () {
OffsetManager.addOffsetListener(p_oOffset, function () {
that.stop(false);
});
});
}
}
});
});
})();
/res/3.0/scripts/yui/svg/anim-svg-debug.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
YUI.add("anim-svg", function (Y) {
/**
* Object with the names of the transform pseudo attributes.
*/
var PSEUDO_ATTRIBUTES_REGEXP = {
tx: /#tx/g,
ty: /#ty/g,
sx: /#sx/g,
sy: /#sy/g,
r: /#r/g
};
var PSEUDO_ATTRIBUTES_ARRAY = ["tx", "ty", "sx", "sy", "r"];
var N_PSEUDO_ATTRIBUTES = PSEUDO_ATTRIBUTES_ARRAY.length;
var colorBehavior = Y.Anim.behaviors.color;
var svgColors = Y.DOM.SVG_COLORS;
var svgColorBehavior = {
set: function(anim, att, from, to, elapsed, duration, fn) {
if (from in svgColors) {
from = svgColors[from];
}
if (to in svgColors) {
to = svgColors[to];
}
colorBehavior.set(anim, att, from, to, elapsed, duration, fn);
},
get: colorBehavior.get
};
Y.Anim.behaviors.transform = {
set: function (anim, att, from, to, elapsed, duration, fun) {
var txf = anim.get(att + "Template"), val, p,
e = anim._node;
if (txf) {
for (p in to) {
if (to.hasOwnProperty(p)) {
val = fun(elapsed, from[p], to[p] - from[p], duration);
txf = txf.replace(PSEUDO_ATTRIBUTES_REGEXP[p], val);
e[p] = val;
}
}
e.setAttribute(att, txf);
}
},
get: function (anim, att) {
var result = {
tx: 0,
ty: 0,
sx: 1,
sy: 1,
r: 0
};
var e = anim._node;
for (var i = 0; i < N_PSEUDO_ATTRIBUTES; i++) {
var a = PSEUDO_ATTRIBUTES_ARRAY[i];
if (e[a] !== undefined) {
result[a] = e[a];
} else {
e[a] = result[a];
}
}
return result;
}
};
Y.Anim.behaviors.stdDeviation = {
set: function (anim, att, from, to, elapsed, duration, fun) {
var val = [fun(elapsed, from[0], to[0] - from[0], duration),
fun(elapsed, from[1], to[1] - from[1], duration)];
// NOTE: setStdDeviation is more efficient, so use it if available.
// Firefox 3.6 and earlier doesn't have support for setStdDeviation,
// so fallback to setAttribute.
if (anim._node.setStdDeviation) {
anim._node.setStdDeviation(val[0], val[1]);
} else {
anim._node.setAttribute(att, val[0] + " " + val[1]);
}
},
get: function (anim, attr) {
// NOTE: Got errors in {Firefox, Opera, Safari} about stdDeviationX
// not being defined in some cases, fallback to the default value [0,0].
var result = [0, 0];
if (anim._node.stdDeviationX !== null &&
anim._node.stdDeviationY !== undefined) {
result = [anim._node.stdDeviationX.baseVal,
anim._node.stdDeviationY.baseVal];
}
return result;
}
};
var lengthBehavior = {
set: function (anim, att, from, to, elapsed, duration, fun) {
var val = fun(elapsed, Number(from), Number(to) - Number(from), duration);
anim._node.set(att, val);
},
get: function (anim, attr) {
return anim._node.get(attr);
}
};
var pathCommands = {
m: 'm',
M: 'M',
l: 'l',
L: 'L',
h: 'h',
H: 'H',
v: 'v',
V: 'V',
q: 'q',
Q: 'Q',
c: 'c',
C: 'C',
z: 'z',
Z: 'Z',
s: 's',
S: 'S',
t: 't',
T: 'T',
a: 'a',
A: 'A'
};
function parsePath (d) {
var n;
if (typeof d === "string") {
d = d.replace(/([^ ])([hHvVmMlLtTqQsScCaAzZ])/g, '$1 $2')
.replace(/([hHvVmMlLtTqQsScCaAzZ])([^ ])/g, '$1 $2')
.replace(/([^ ,])-/g, '$1,-')
.replace(/[ ]{2,}/g, ' ')
.replace(/[ ]+/g,',').split(',');
n = d.length;
for (var i = 0; i < n; i++) {
if (pathCommands[d[i]] === undefined) {
d[i] = Number(d[i]);
}
}
}
return d;
}
Y.Anim.behaviors.d = {
set: function (anim, att, from, to, elapsed, duration, fun) {
from = parsePath(from);
to = parsePath(to);
// As in the SVG specification, it is a requirement that the path
// segment types match. So we only need to interpolate the coordinates.
var n = to.length,
c,
v = [],
nc,
is,
max;
for (var i = 0; i < n;) {
c = to[i]; // command
v.push(c);
nc = 0;
is = i + 1;
switch (c) {
case 'h':
case 'H':
case 'v':
case 'V':
i++;
do {
i++;
nc++;
} while (typeof to[i] === "number");
break;
case 'm':
case 'M':
case 'l':
case 'L':
case 't':
case 'T':
i++;
do {
i += 2;
nc += 2;
} while (typeof to[i] === "number");
break;
case 'q':
case 'Q':
case 's':
case 'S':
i++;
do {
i += 4;
nc += 4;
} while (typeof to[i] === "number");
break;
case 'c':
case 'C':
i++;
do {
i += 6;
nc += 6;
} while (typeof to[i] === "number");
break;
case 'a':
case 'A':
i++;
do {
i += 7;
nc += 7;
} while (typeof to[i] === "number");
break;
// case 'z':
// case 'Z':
default:
// Includes 'z' and 'Z'
i += 1;
break;
}
max = is + nc;
for (var j = is; j < max; j++) {
v[j] = fun(elapsed, from[j], to[j] - from[j], duration);
if (isNaN(v[j]) === true) {
Y.log('v[' + j + '] is NaN');
}
}
}
anim._node.setAttribute(att, v.join(' '));
},
get: function (anim, attr) {
return parsePath(anim._node.getAttribute(attr));
}
};
Y.Anim.behaviors.fill = svgColorBehavior;
Y.Anim.behaviors.stroke = svgColorBehavior;
Y.Anim.behaviors["stop-color"] = svgColorBehavior;
Y.Anim.behaviors["flood-color"] = svgColorBehavior;
Y.Anim.behaviors["lighting-color"] = svgColorBehavior;
Y.Anim.behaviors.dy = lengthBehavior;
Y.Anim.behaviors.y = lengthBehavior;
Y.Anim.behaviors.dx = lengthBehavior;
Y.Anim.behaviors.x = lengthBehavior;
Y.Anim.behaviors.rotate = lengthBehavior;
Y.Anim.behaviors.width = lengthBehavior;
Y.Anim.behaviors.height = lengthBehavior;
Y.Anim.behaviors.r = lengthBehavior;
Y.Anim.behaviors.rx = lengthBehavior;
Y.Anim.behaviors.ry = lengthBehavior;
Y.Anim.behaviors.cx = lengthBehavior;
Y.Anim.behaviors.cy = lengthBehavior;
Y.Anim.behaviors.x1 = lengthBehavior;
Y.Anim.behaviors.x2 = lengthBehavior;
Y.Anim.behaviors.y1 = lengthBehavior;
Y.Anim.behaviors.y2 = lengthBehavior;
Y.Anim.behaviors.offset = lengthBehavior;
});