Animated lyrics
Song lines swell, turn and fade along a wavy SVG path while rings pulse on the beat, timed to music synthesized in your browser.
What you are seeing
A crimson radial background with black ink splashes along the bottom. After you press play, lowercase lines of a short song about a paper lantern grow across the stage on a wavy path, turn slowly and fade, while white concentric rings pulse at random positions on each beat. The current line also appears as a plain caption above a control bar with play, stop, lyrics and a progress bar. The full words are available in a lyrics panel.
How it works
Each lyric line is an SVG text element with a textPath that follows one wavy curve.
Vincent Hardy's animation chain scales and rotates a line in, drifts it outward while it fades, then speeds it off the stage.
A small Web Audio synthesizer schedules pads, bass, plucked arpeggios, a lead melody and soft percussion when you press play.
The AudioContext clock decides when each line and beat ring starts, so pausing the sound also holds the picture.
History
Published on October 4, 2009. The original played a commercially licensed song and displayed its lyrics. That recording, its words, the artist photos and the licensed display fonts are not part of this version.
Source
/audio/animated-lyrics.svg
<?xml version="1.0" encoding="utf-8"?>
<!-- ======================================================================= -->
<!-- Vincent Hardy -->
<!-- License terms: see svg-wow.org -->
<!-- CC0 http://creativecommons.org/publicdomain/zero/1.0/ -->
<!-- Restored with an original song synthesized by song-synth.js. -->
<!-- ======================================================================= -->
<?xml-stylesheet type="text/css" href="animated-lyrics.css" ?>
<svg width="100%" height="100%" viewBox="0 0 800 550"
preserveAspectRatio="xMidYMid meet"
style="background:#000"
xmlns="http://www.w3.org/2000/svg"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Animated lyrics</title>
<desc>Lines of a short song swell, turn and fade along a wavy path over a crimson background with ink splashes, while rings pulse on each beat. The song is Paper lantern tide, written and synthesized for this restoration. Its words are: a paper lantern on the tide, carries the evening out to sea, i set my small light by its side, and let the dark come close to me, the harbor hums a quiet tone, the ropes keep time against the mast, no shore is ever quite alone, while one slow lantern drifts on past. Press play, or space, to start. S stops. L shows the lyrics.</desc>
<rect x="0%" y="0%" width="100%" height="100%" fill="black" />
<svg width="800" height="550" viewBox="400 275 800 550"
id="root" x="50%" y="50%"
xmlns="http://www.w3.org/2000/svg"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:sw="http://www.svgopen.org/2004/svgWow"
xmlns:xlink="http://www.w3.org/1999/xlink"
overflow="visible">
<script><![CDATA[
// YUI 2 registers an unload handler, which current browsers reject.
// Nothing in this demo needs it.
(function () {
var add = window.addEventListener;
window.addEventListener = function (type) {
if (type !== "unload") {
return add.apply(this, arguments);
}
};
})();
]]></script>
<script xlink:href="../res/2.0/scripts/yui/yahoo-dom-event/yahoo-dom-event.js" />
<script xlink:href="../res/2.0/scripts/yui/animation/animation-min.js" />
<script xlink:href="../res/2.0/scripts/dom-utils.js" />
<script xlink:href="../res/2.0/scripts/animation/animate.js" />
<script xlink:href="audio-collection.js" />
<script xlink:href="music/paper-lantern/paper-lantern.js" />
<script xlink:href="song-synth.js" />
<script xlink:href="animated-lyrics.js" />
<!-- The original audio element; sound now comes from song-synth.js. -->
<g id="trackHTML5" />
<defs>
<clipPath id="viewportClip">
<rect width="800" height="550" />
</clipPath>
<radialGradient id="backgroundFill" cx=".50" cy="0.50" r="1"
gradientUnits="objectBoundingBox">
<stop offset="0" stop-color="rgb(244,159,155)" />
<stop offset="0.5" stop-color="rgb(109,0,38)" />
<stop offset="1" stop-color="black" />
</radialGradient>
<linearGradient id="attributionsFill" x1="0" y1="0" x2="0" y2="1"
gradientUnits="objectBoundingBox">
<stop offset="0" stop-color="black" stop-opacity="0.7"/>
<stop offset="1" stop-color="black" stop-opacity="0.2" />
</linearGradient>
<linearGradient id="attributionsStroke" x1="0" y1="0" x2="1" y2="1"
gradientUnits="objectBoundingBox">
<stop offset="0" stop-color="black" stop-opacity="0.1"/>
<stop offset="1" stop-color="black" stop-opacity="0.8" />
</linearGradient>
<path id="linePath" d="M -400 0 Q -300 -100 -200 0 Q -100 100 0 0
Q 100 -100 200 0 Q 300 100 400 0" />
<pattern id="imagePattern" patternUnits="userSpaceOnUse" x="0" y="0"
width="800" height="550" >
<image xlink:href="background.png" width="800" height="550" />
</pattern>
</defs>
<g clip-path="url(#viewportClip)">
<rect id="bgFill" fill="url(#imagePattern)" rx="10" ry="10"
width="100%" height="100%"/>
<rect id="cast" fill="black" fill-opacity="0.75"
width="100%" height="100%"/>
<defs>
</defs>
<g id="credits" class="credits" transform="translate(400, -110)">
<g transform="translate(-115,-50)">
<rect rx="5" ry="5" fill="black" fill-opacity="0.5"
width="230" height="60" />
<g transform="translate(30,30)" fill="none" stroke="#ffd24a" stroke-width="2">
<path d="M -10 -11 Q -17 0 -10 11 L 10 11 Q 17 0 10 -11 Z" fill="#ffd24a" fill-opacity="0.3"/>
<path d="M -4 -11 Q -8 0 -4 11 M 4 -11 Q 8 0 4 11 M 0 -11 V -17"/>
</g>
<text x="60" y="26" class="h1">song: paper lantern tide</text>
<text x="60" y="42"
class="h2">new words and music, 2026</text>
</g>
</g>
<g id="credits2" class="credits" transform="translate(400, 600)">
<g transform="translate(-115,-50)">
<rect rx="5" ry="5" fill="black" fill-opacity="0.5"
width="230" height="60" />
<g transform="translate(30,30)" fill="none" stroke="#ffb3c7" stroke-width="2">
<circle r="5"/><circle r="10"/><circle r="15"/>
</g>
<text x="60" y="26" class="h1">animation engine</text>
<text x="60" y="42" class="h2">by vincent hardy - 2009</text>
</g>
</g>
<g text-anchor="middle" fill="white" stroke="white"
transform="translate(400,275)" id="beats">
</g>
<g text-anchor="middle" fill="white" fill2="rgb(254,187,6)" stroke="none"
font-size="26"
font-family="'Trebuchet MS','Avenir Next','Myriad Pro', Myriad, Helvetica, sans-serif"
font-weight="bold"
transform="translate(320,240)" id="songText">
</g>
<g transform="translate(400,275)">
<g id="attributionsGroup" >
</g>
</g>
</g>
<!-- Kept for its id. The synthesized song has nothing to load. -->
<g id="loadingAudioMessage" display="none">
<g id="loadingAudio">
<circle id="waitSpoke" cx="10" r="2" />
</g>
</g>
</svg>
<g id="instructions" font-family="Arial,Helvetica,sans-serif"
font-weight="bold" text-anchor="middle" display="inline" fill="white">
<text x="400" y="150" font-size="18">
<tspan>click to start the song</tspan>
<tspan x="400" dy="1.3em" font-weight="normal" font-size="14">sound plays after you click</tspan>
</text>
</g>
<text id="caption" x="400" y="486" role="status" aria-live="polite"></text>
<g id="lyricsPanel" display="none" transform="translate(432,58)" role="region" aria-label="Lyrics">
<rect width="356" height="388" rx="8" fill="black" fill-opacity="0.82" stroke="white" stroke-opacity="0.35"/>
<text x="18" y="30" class="lyricTitle">Paper lantern tide</text>
<g id="lyricsLines"></g>
</g>
<g id="controlBar" transform="translate(0,500)">
<rect id="controlBack" width="800" height="50" fill="black" fill-opacity="0.62"/>
<g id="controlButtons">
<g id="btnPlay" class="control" role="button" tabindex="0" aria-label="Play" transform="translate(14,8)">
<rect width="44" height="34" rx="6"/>
<path id="iconPlay" d="M 16 9 L 32 17 L 16 25 Z" fill="white"/>
<path id="iconPause" d="M 15 9 H 20 V 25 H 15 Z M 25 9 H 30 V 25 H 25 Z" fill="white" display="none"/>
</g>
<g id="btnStop" class="control" role="button" tabindex="0" aria-label="Stop" transform="translate(66,8)">
<rect width="44" height="34" rx="6"/>
<path d="M 15 10 H 29 V 24 H 15 Z" fill="white"/>
</g>
<g id="btnLyrics" class="control" role="button" tabindex="0" aria-label="Show lyrics" aria-pressed="false" transform="translate(118,8)">
<rect width="70" height="34" rx="6"/>
<text class="controlLabel" x="35" y="22">Lyrics</text>
</g>
</g>
<g id="progressGroup" transform="translate(206,21)" aria-hidden="true">
<rect width="400" height="8" rx="4" fill="white" fill-opacity="0.25"/>
<rect id="progressFill" width="0" height="8" rx="4" fill="#ffd24a"/>
</g>
<text id="timeText" x="622" y="30">0:00 / 0:00</text>
</g>
<script><![CDATA[
sw.init();
sw.animatedLyrics.init();
]]></script>
</svg>
/audio/animated-lyrics.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
*
* Restoration notes: the line and beat animations are the original code.
* The audio element is replaced by a Web Audio synthesizer, the audio clock
* now triggers lines and beats, and play, pause, stop and lyrics controls
* are added.
* ======================================================================= */
var sw = sw || {};
sw.animatedLyrics = sw.animatedLyrics || {};
sw.animatedLyrics.init = function () {
var BaseAnimate = sw.animation.Animate;
var allAnimations = [];
// Keeps a list of every animation so that stop can cancel them.
var Animate = function (p_el, p_attributes, p_duration, p_method) {
var a = new BaseAnimate(p_el, p_attributes, p_duration, p_method);
allAnimations.push(a);
return a;
};
var synth = sw.audio.synth;
var reduceMotion = !!(window.matchMedia &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches);
var state = "idle"; // idle, playing, paused or ended
var playList = [];
var lineNodes = [];
var beatList = [];
var beatPos = [];
var beatListSize = 20;
var previousOffset = 0;
var song = sw.audio.collection.getSongs()[0];
var nLines = song.timing.length;
var songText = $("songText");
var beats = $("beats");
var nextFadeInEnd = undefined;
var fadeInDur = 0.4;
var speedFadeOutDur = 0.4;
var fadeOutDur = 7;
var minFadeOutDur = speedFadeOutDur + 0.2;
var curFadeInDur;
var curFadeOutDur;
var p;
var fadeIn;
var fadeOut;
var speedFadeOut;
var s;
var nextBeat = -1;
var nextLine = 0;
var attributionsAnim;
var startBeat;
var durationMs = synth.duration() * 1000;
// The YUI animation manager runs on wall-clock time. These hooks hold it
// while the audio is paused and shift each running animation's start time
// by the length of the pause, so that sound and picture stay together.
var AnimMgr = yui.util.AnimMgr;
var mgrRun = AnimMgr.run;
var mgrRegister = AnimMgr.registerElement;
var pausedAt = null;
var pausedTotal = 0;
AnimMgr.run = function () {
if (pausedAt === null) {
mgrRun.call(AnimMgr);
}
};
AnimMgr.registerElement = function (p_tween) {
if (p_tween.getStartTime && !p_tween.swClock) {
var originalStart = p_tween.getStartTime;
p_tween.swClock = true;
p_tween.getStartTime = function () {
return +originalStart.call(p_tween) +
(pausedTotal - p_tween.swPauseBase);
};
}
p_tween.swPauseBase = pausedTotal;
return mgrRegister.call(AnimMgr, p_tween);
};
var beatTween = {
_onStart: {
fire: function() {}
},
isAnimated : function () { return true; },
currentFrame : 0,
totalFrames : null,
useSeconds : false,
_onTween : {
fire: function() {
tick();
}
}
};
yui.util.AnimMgr.registerElement(beatTween);
if (song.timingOffset === undefined) {
song.timingOffset = 0;
}
for (var i = 0; i < nLines; i++) {
var l = song.timing[i];
var t = document.createElementNS(sw.svgNS, 'text');
var tp = document.createElementNS(sw.svgNS, 'textPath');
t.appendChild(tp);
tp.appendChild(document.createTextNode(l[1].toLowerCase()));
tp.setAttribute("startOffset", (36 + 28 * Math.random()) + "%");
// tp.setAttribute("text-anchor", "middle");
tp.setAttributeNS(sw.xlinkNS, "href", "#linePath");
if (i < nLines - 1) {
// Timing is in milliseconds
nextFadeInEnd = (song.timing[i + 1][0] - l[0]) / 1000 + fadeInDur;
}
curFadeInDur = Math.min(fadeInDur, nextFadeInEnd);
fadeIn = new Animate(t, {
txf: {
from: {sx: 0.2, r: 80 * (Math.random() - 0.5)},
to: {sx: 1.3, r: 0},
template: "scale(#sx) rotate(#r)"
}
}, curFadeInDur, yui.util.Easing.easeIn);
fadeIn.onBegin(getStartHandler(t, songText));
curFadeOutDur = Math.min(fadeOutDur, nextFadeInEnd - curFadeInDur);
if (curFadeOutDur > minFadeOutDur) {
// We have time for a slow fade out phase. We want a slow speed,
// even if se do not have the full fadeOutDur.
p = curFadeOutDur / fadeOutDur;
s = 5 * p + 1.3 * (1 - p);
fadeOut = new Animate(t, {
txf: {
to: {sx: s},
by: {r: 80 * (Math.random() - 0.5)},
template: "scale(#sx) rotate(#r)"
},
opacity: {from: 1, to: 0}
}, curFadeOutDur, undefined);
fadeIn.onEnd(fadeOut);
if (p < 1) {
speedFadeOut = new Animate(t, {
opacity: {to: 0},
txf: {
from: {sx: s},
to: {sx: 5},
by: {r: 80 * (Math.random() - 0.5)},
template: "scale(#sx) rotate(#r)"
}
}, speedFadeOutDur, undefined);
fadeOut.onEnd(speedFadeOut);
speedFadeOut.onEnd(getStopHandler(t, songText));
} else {
fadeOut.onEnd(getStopHandler(t, songText));
}
} else {
// No time for slow fade out. Speed the line out.
speedFadeOut = new Animate(t, {
opacity: {to: 0},
txf: {
to: {sx: 5, r: 60 * (Math.random() - 0.5)},
template: "scale(#sx) rotate(#r)"
}
}, speedFadeOutDur, undefined);
fadeIn.onEnd(speedFadeOut);
speedFadeOut.onEnd(getStopHandler(t, songText));
}
fadeIn.offset = l[0];
fadeIn.deltaOffset = fadeIn.offset - previousOffset;
previousOffset = fadeIn.offset;
playList.push(fadeIn);
lineNodes.push(t);
t.setAttribute('y', (-100 + Math.random()*200));
t.setAttribute("transform", "scale(0.2,0.2)")
}
for (i = 0; i < song.beats.length; i++) {
beatPos.push({
x: 700 * (Math.random() - 0.5),
y: 500 * (Math.random() - 0.5)
});
}
for (i = 0; i < beatListSize; i++) {
var beat = sw.loadContent.call(null, {
tag: "g",
opacity: 0.25,
children: [
{
tag: "circle",
r: 5,
fill: "none",
"stroke-width": 3
},
{
tag: "circle",
r: 8,
fill: "none",
"stroke-width": 2
},
{
tag: "circle",
r: 12,
fill: "none",
"stroke-width": 4
}
]
});
startBeat = new Animate(beat, {
txf: {
from: {sx: 1, sy: 1},
to: {sx: 2, sy: 2},
template: "scale(#sx, #sy)"
}
}, 0.75, yui.util.Easing.elasticOut);
beatList.push(startBeat);
startBeat.onBegin(getStartHandler(beat, beats));
startBeat.onEnd(getStopHandler(beat, beats));
}
var attributionsGroup = $("attributionsGroup");
buildAttributions();
function getStartHandler(t, c) {
return function () {
c.appendChild(t);
};
}
function getStopHandler(t, c) {
return function () {
if (t.parentNode === c) {
c.removeChild(t);
}
};
}
function getBeatStartHandler (beatIndex) {
var beatListIndex = beatIndex % beatList.length;
var beat = beatList[beatListIndex];
var scale = 2 + 5 * Math.random();
return function () {
beat.stop();
beat.attributes.txf.to.sx = scale;
beat.attributes.txf.to.sy = scale;
beat.getEl().setAttribute("transform",
"translate(" + beatPos[beatIndex].x +
"," + beatPos[beatIndex].y + ")");
beat.attributes.txf.template = "translate(" + beatPos[beatIndex].x + "," +
beatPos[beatIndex].y + ") scale(#sx,#sy)";
beat.animate();
}
}
function checkStartBeat (curOffset) {
if (nextBeat === -1) {
return;
}
var nextBeatOffset = song.beats[nextBeat];
nextBeatOffset += song.timingOffset;
if (curOffset >= nextBeatOffset) {
// After a stall, such as a hidden tab, skip to the current beat.
while (nextBeat + 1 < song.beats.length &&
curOffset >= song.beats[nextBeat + 1] + song.timingOffset) {
nextBeat++;
}
if (!reduceMotion) {
var startHandler = getBeatStartHandler(nextBeat);
startHandler();
}
nextBeat++;
if (nextBeat >= song.beats.length) {
nextBeat = -1;
showCast.animate();
}
}
}
function checkStartLine (curOffset) {
var due = -1;
while (nextLine < nLines &&
curOffset >= playList[nextLine].offset + song.timingOffset) {
due = nextLine++;
}
if (due !== -1) {
if (!reduceMotion) {
playList[due].animate();
}
showLine(due);
}
}
/**
* Called on each animation frame. The audio clock decides what is due.
*/
function tick () {
if (state !== "playing") {
return;
}
var curOffset = synth.time() * 1000;
checkStartLine(curOffset);
checkStartBeat(curOffset);
showProgress(curOffset);
if (curOffset >= durationMs) {
finish();
}
}
function play () {
if (state === "playing") {
pause();
} else if (state === "paused") {
resume();
} else {
begin();
}
}
function begin () {
if (state === "ended") {
resetStage();
}
synth.start();
state = "playing";
nextBeat = 0;
nextLine = 0;
$("instructions").setAttribute("display", "none");
hideCredits.animate();
showState();
}
function pause () {
synth.pause();
pausedAt = Date.now();
state = "paused";
showState();
}
function resume () {
synth.resume();
pausedTotal += Date.now() - pausedAt;
pausedAt = null;
state = "playing";
showState();
}
function stop () {
if (pausedAt !== null) {
pausedTotal += Date.now() - pausedAt;
pausedAt = null;
}
synth.stop();
resetStage();
state = "idle";
$("instructions").setAttribute("display", "inline");
showState();
}
function finish () {
synth.stop();
state = "ended";
showLine(-1);
showProgress(durationMs);
showState();
}
function quietStop (a) {
if (a.isAnimated()) {
var ends = a._endCallbacks.splice(0);
var chained = a._endAnimations.splice(0);
a.stop();
Array.prototype.push.apply(a._endCallbacks, ends);
Array.prototype.push.apply(a._endAnimations, chained);
}
}
function resetStage () {
allAnimations.forEach(quietStop);
songText.removeAllChildren();
beats.removeAllChildren();
lineNodes.forEach(function (n) {
n.style.opacity = "";
n.setAttribute("transform", "scale(0.2,0.2)");
});
var cast = $("cast");
cast.style.opacity = "";
cast.style.fillOpacity = "";
cast.setAttribute("display", "inline");
attributionsGroup.setAttribute("display", "inline");
attributionsGroup.removeAttribute("transform");
var c = attributionsGroup.firstElementChild;
while (c !== null) {
c.setAttribute("display", "none");
c = c.nextElementSibling;
}
nextBeat = -1;
nextLine = 0;
placeCredits();
showLine(-1);
showProgress(0);
}
// Controls and accessible lyrics
// =========================================================================
var caption = $("caption");
var lyricRows = [];
var lyricsList = $("lyricsLines");
song.lyrics.forEach(function (line, index) {
lyricRows.push(lyricsList.loadContent({
tag: "text",
x: 18,
y: 62 + index * 40,
"class": "lyricRow",
children: [line]
}));
});
function showLine (index) {
caption.textContent = index >= 0 ? song.lyrics[index] : "";
lyricRows.forEach(function (row, r) {
row.setAttribute("class", r === index ? "lyricRow current" : "lyricRow");
});
}
function clockText (ms) {
var total = Math.floor(ms / 1000);
var seconds = total % 60;
return Math.floor(total / 60) + ":" + (seconds < 10 ? "0" : "") + seconds;
}
function showProgress (ms) {
var f = Math.max(0, Math.min(1, ms / durationMs));
$("progressFill").setAttribute("width", 400 * f);
$("timeText").textContent = clockText(ms) + " / " + clockText(durationMs);
}
function showState () {
var playing = state === "playing";
var label = playing ? "Pause" : (state === "paused" ? "Resume" : (state === "ended" ? "Play again" : "Play"));
$("btnPlay").setAttribute("aria-label", label);
$("iconPlay").setAttribute("display", playing ? "none" : "inline");
$("iconPause").setAttribute("display", playing ? "inline" : "none");
document.documentElement.setAttribute("data-state", state);
}
function toggleLyrics () {
var panel = $("lyricsPanel");
var open = panel.getAttribute("display") === "none";
panel.setAttribute("display", open ? "inline" : "none");
$("btnLyrics").setAttribute("aria-pressed", open ? "true" : "false");
}
/**
* Keeps the controls at a usable touch size. In portrait the stage stays
* whole and the caption and controls move into the space below it.
*/
function layout () {
var w = window.innerWidth;
var h = window.innerHeight;
var portrait = h > w * 1.1;
var viewHeight = portrait ? 810 : 550;
var scale = Math.min(w / 800, h / viewHeight);
var small = !portrait && scale < 0.8;
var bar = portrait ? {y: 625, h: 185, k: 2.6, px: 36, py: 132, pw: 470, tx: 764, ty: 150, ts: 30}
: small ? {y: 470, h: 80, k: 1.6, px: 326, py: 36, pw: 300, tx: 786, ty: 47, ts: 20}
: {y: 500, h: 50, k: 1, px: 206, py: 21, pw: 400, tx: 786, ty: 30, ts: 13};
var panel = portrait ? "translate(115,2) scale(1.6)"
: small ? "translate(362,6) scale(1.13)"
: "translate(432,58)";
document.documentElement.setAttribute("viewBox", "0 0 800 " + viewHeight);
$("controlBar").setAttribute("transform", "translate(0," + bar.y + ")");
$("controlBack").setAttribute("height", bar.h);
$("controlButtons").setAttribute("transform", "scale(" + bar.k + ")");
$("progressGroup").setAttribute("transform",
"translate(" + bar.px + "," + bar.py + ") scale(" + (bar.pw / 400) + ",1)");
var time = $("timeText");
time.setAttribute("x", bar.tx);
time.setAttribute("y", bar.ty);
time.setAttribute("text-anchor", "end");
time.style.fontSize = bar.ts + "px";
caption.setAttribute("y", portrait ? 596 : (small ? 460 : 486));
caption.style.fontSize = (portrait ? 34 : (small ? 25 : 18)) + "px";
$("lyricsPanel").setAttribute("transform", panel);
}
function bindButton (id, action) {
var b = $(id);
b.addEventListener("click", function (evt) {
evt.stopPropagation();
action();
}, false);
b.addEventListener("keydown", function (evt) {
if (evt.key === " " || evt.key === "Enter") {
evt.preventDefault();
evt.stopPropagation();
action();
}
}, false);
}
bindButton("btnPlay", play);
bindButton("btnStop", function () {
if (state !== "idle") {
stop();
}
});
bindButton("btnLyrics", toggleLyrics);
// A click on the stage plays or pauses, as the original click did.
document.documentElement.addEventListener("click", function (evt) {
if (evt.target.closest && evt.target.closest("#controlBar, #lyricsPanel, a")) {
return;
}
play();
}, false);
document.addEventListener("keydown", function (evt) {
if (evt.ctrlKey || evt.metaKey || evt.altKey) {
return;
}
if (evt.key === " ") {
evt.preventDefault();
play();
} else if (evt.key === "s" || evt.key === "S") {
if (state !== "idle") {
stop();
}
} else if (evt.key === "l" || evt.key === "L") {
toggleLyrics();
}
}, false);
function buildAttributions () {
var attributions = song.attributions;
var attributionLines;
var curLine = -0.5;
var curGroup;
var prevFadeOut;
var firstFadeIn;
var fadeIn;
var fadeOut;
var show;
var lastFadeOut;
for (var p in attributions) {
if (attributions.hasOwnProperty(p) === true) {
attributionLines = attributions[p].split("\n");
curGroup = attributionsGroup.loadContent({
tag: "g"
});
curGroup.loadContent({
tag: "text",
"class": "attributionType",
y: (curLine++ * 1.1) + "em",
children: [p]
});
for (var i = 0; i < attributionLines.length; i++) {
curGroup.loadContent({
tag: "text",
"class": "attributionValue",
y: (curLine++ * 1.1) + "em",
children: [attributionLines[i]]
});
}
fadeIn = new Animate(attributionsGroup, {
txf: {
template: "scale(1, #sy)",
from: {sy: 0.01},
to: {sy: 1}
}
}, 2, yui.util.Easing.elasticOut);
show = new Animate(attributionsGroup, {
txf: {
from: {sy: 1},
to: {sy: 1},
template: "scale(1, 1)"
}
}, 1, undefined);
fadeOut = new Animate(attributionsGroup, {
txf: {
from: {sy: 1},
tp: {sy: 0.01},
template: "scale(1, #sy)"
}
}, 0.25, yui.util.Easing.backIn);
fadeIn.onBegin(curGroup.getShowHandler());
fadeIn.onEnd(show);
show.onEnd(fadeOut);
fadeOut.onEnd(curGroup.getHideHandler());
lastFadeOut = fadeOut;
if (firstFadeIn === undefined) {
firstFadeIn = fadeIn;
} else {
prevFadeOut.onEnd(fadeIn);
}
prevFadeOut = fadeOut;
curLine = -0.5;
}
}
lastFadeOut.onEnd(attributionsGroup.getHideHandler());
// Add a background rectangle
var bbox = attributionsGroup.getBBox();
var firstChild = attributionsGroup.firstElementChild;
var padding = 10;
var bkg = attributionsGroup.loadContent({
tag: "rect",
x: -190,
y: bbox.y - padding,
width: 380,
height: bbox.height + 2 * padding,
fill: "url(#attributionsFill)",
"fill-opacity": 0.5,
stroke: "url(#attributionsStroke)",
"stroke-opacity": 0.5,
"stroke-width": 1,
rx: 5,
ry: 5,
display: "none"
}, firstChild);
var c = firstChild;
while (c !== null) {
c.setAttribute("display", "none");
c = c.nextElementSibling;
}
firstFadeIn.onBegin(bkg.getShowHandler());
attributionsAnim = firstFadeIn;
}
var showCredits = new Animate("credits", {
txf: {
to: {ty: 250, r: 0},
from: {r: 180},
template: 'translate(400,#ty) rotate(#r)'
}
}, 1.2, yui.util.Easing.elasticOut);
var showCredits2 = new Animate("credits2", {
txf: {
to: {ty: 320, r: 0},
from: {r: -180},
template: 'translate(400,#ty) rotate(#r)'
}
}, 1, yui.util.Easing.elasticOut);
showCredits.onBegin(showCredits2);
var hideCredits = new Animate("credits", {
txf: {
to: {ty: 600},
template: 'translate(400,#ty)'
}
}, 0.6, yui.util.Easing.backIn);
var hideCredits2 = new Animate("credits2", {
txf: {
to: {ty: 600},
template: 'translate(400,#ty)'
}
}, 0.5, yui.util.Easing.backIn);
var hideCast = new Animate("cast", {
"fill-opacity": {
from: 0.75,
to: 0
},
"opacity": {
from: 0.75,
to: 0
}
}, 3);
var showCast = new Animate("cast", {
"fill-opacity": {from: 0, to: 0.75},
opacity: {from: 0, to: 0.75}}, 3);
hideCredits.onBegin(hideCredits2);
hideCredits.onBegin(hideCast);
showCast.onBegin(attributionsAnim);
showCast.onBegin($("cast").getShowHandler());
hideCast.onEnd($("cast").getHideHandler());
function placeCredits () {
var a = $("credits");
var b = $("credits2");
a.ty = 250; a.r = 0;
b.ty = 320; b.r = 0;
a.setAttribute("transform", "translate(400,250) rotate(0)");
b.setAttribute("transform", "translate(400,320) rotate(0)");
}
window.addEventListener("resize", layout, false);
layout();
showState();
showProgress(0);
if (reduceMotion) {
placeCredits();
} else {
showCredits.animate();
}
/** Read-only view of the player, used by the automated browser checks. */
sw.animatedLyrics.status = function () {
return {
state: state,
time: synth.time(),
nextLine: nextLine,
nextBeat: nextBeat,
caption: caption.textContent,
linesOnStage: songText.childNodes.length,
ringsOnStage: beats.childNodes.length
};
};
};
/audio/animated-lyrics.css
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* Restoration: the licensed display font is replaced by a system stack.
* ======================================================================= */
:root {
background: #000;
}
.credits {
font-family: Arial,Helvetica,sans-serif;
fill: white;
}
.h1 {
fill: white;
font-size: 14px;
font-weight: bold;
}
.h2 {
font-size: 10px;
font-weight: normal;
padding: 0px;
margin: 0px;
fill: #ffb3c7;
}
.attributionType {
font-family: "Trebuchet MS", "Avenir Next", Verdana, sans-serif;
font-size: 24px;
font-weight: normal;
fill: #ff8fa8;
text-anchor: middle;
}
.attributionValue {
font-family: "Trebuchet MS", "Avenir Next", Verdana, sans-serif;
font-size: 26px;
fill: white;
text-anchor: middle;
}
#caption {
font-family: "Trebuchet MS", "Avenir Next", Verdana, sans-serif;
font-size: 18px;
fill: white;
text-anchor: middle;
paint-order: stroke;
stroke: rgba(0, 0, 0, 0.75);
stroke-width: 4px;
}
#controlBar text, #lyricsPanel text {
font-family: "Trebuchet MS", "Avenir Next", Verdana, sans-serif;
}
.control {
cursor: pointer;
outline: none;
}
.control rect {
fill: rgba(255, 255, 255, 0.14);
stroke: rgba(255, 255, 255, 0.55);
stroke-width: 1;
}
.control:hover rect {
fill: rgba(255, 255, 255, 0.28);
}
.control:focus-visible rect {
stroke: #ffd24a;
stroke-width: 3;
}
.controlLabel {
fill: white;
font-size: 14px;
text-anchor: middle;
}
#timeText {
fill: white;
font-size: 13px;
}
.lyricTitle {
fill: #ffb3c7;
font-size: 15px;
font-weight: bold;
}
.lyricRow {
fill: rgba(255, 255, 255, 0.82);
font-size: 16px;
}
.lyricRow.current {
fill: #ffd24a;
font-weight: bold;
}
/audio/song-synth.js
/* Runtime synthesizer for the animated lyrics demo. All sound is generated
* here with Web Audio; no recording is loaded. The AudioContext clock is the
* master clock for the lyric animation. Released under CC0. */
(function () {
sw.audio = sw.audio || {};
function hz(midi) {
return 440 * Math.pow(2, (midi - 69) / 12);
}
// Small seeded generator so the reverb and shaker are the same on each run.
function rng(seed) {
var s = seed >>> 0;
return function () {
s = (s + 0x6D2B79F5) >>> 0;
var t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function impulse(ctx, seconds, decay) {
var rate = ctx.sampleRate;
var length = Math.floor(rate * seconds);
var buffer = ctx.createBuffer(2, length, rate);
var random = rng(2009);
for (var c = 0; c < 2; c++) {
var data = buffer.getChannelData(c);
for (var i = 0; i < length; i++) {
data[i] = (random() * 2 - 1) * Math.pow(1 - i / length, decay);
}
}
return buffer;
}
function noise(ctx) {
var length = Math.floor(ctx.sampleRate * 0.2);
var buffer = ctx.createBuffer(1, length, ctx.sampleRate);
var data = buffer.getChannelData(0);
var random = rng(88);
for (var i = 0; i < length; i++) {
data[i] = random() * 2 - 1;
}
return buffer;
}
function envelope(param, t, attack, peak, end) {
param.setValueAtTime(0.0001, t);
param.exponentialRampToValueAtTime(peak, t + attack);
param.exponentialRampToValueAtTime(0.0001, end);
}
/**
* Schedules the whole score on a context, starting at time t0. Works with
* both AudioContext and OfflineAudioContext.
*/
function schedule(ctx, output, t0, score) {
var beat = 60 / score.bpm;
var master = ctx.createGain();
master.gain.value = 0.85;
var compressor = ctx.createDynamicsCompressor();
compressor.threshold.value = -16;
compressor.ratio.value = 3;
master.connect(compressor);
compressor.connect(output);
var reverb = ctx.createConvolver();
reverb.buffer = impulse(ctx, 1.8, 2.6);
var wet = ctx.createGain();
wet.gain.value = 0.28;
reverb.connect(wet);
wet.connect(master);
function voice(level, send) {
var g = ctx.createGain();
g.gain.value = level;
g.connect(master);
if (send) {
var s = ctx.createGain();
s.gain.value = send;
g.connect(s);
s.connect(reverb);
}
return g;
}
var padBus = voice(1, 0.7);
var bassBus = voice(1, 0.1);
var arpBus = voice(1, 0.6);
var leadBus = voice(1, 0.55);
var drumBus = voice(1, 0.15);
var shakerBuffer = noise(ctx);
function pad(t, dur, notes) {
var filter = ctx.createBiquadFilter();
filter.type = "lowpass";
filter.Q.value = 0.6;
filter.frequency.setValueAtTime(500, t);
filter.frequency.linearRampToValueAtTime(1100, t + dur * 0.6);
filter.frequency.linearRampToValueAtTime(600, t + dur + 0.6);
var g = ctx.createGain();
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(0.05, t + 0.7);
g.gain.setValueAtTime(0.05, t + Math.max(0.7, dur - 0.2));
g.gain.exponentialRampToValueAtTime(0.0001, t + dur + 0.8);
filter.connect(g);
g.connect(padBus);
notes.forEach(function (n) {
[-6, 6].forEach(function (cents) {
var o = ctx.createOscillator();
o.type = "sawtooth";
o.frequency.value = hz(n);
o.detune.value = cents;
o.connect(filter);
o.start(t);
o.stop(t + dur + 0.9);
});
});
}
function bass(t, dur, midi) {
var o = ctx.createOscillator();
var g = ctx.createGain();
o.type = "triangle";
o.frequency.value = hz(midi);
envelope(g.gain, t, 0.02, 0.3, t + dur);
o.connect(g);
g.connect(bassBus);
o.start(t);
o.stop(t + dur + 0.05);
}
function pluck(t, midi, level) {
var o = ctx.createOscillator();
var g = ctx.createGain();
o.type = "triangle";
o.frequency.value = hz(midi);
envelope(g.gain, t, 0.006, level, t + 0.55);
o.connect(g);
g.connect(arpBus);
o.start(t);
o.stop(t + 0.6);
}
function lead(t, dur, midi) {
var end = t + dur + 0.25;
var g = ctx.createGain();
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(0.16, t + 0.03);
g.gain.exponentialRampToValueAtTime(0.1, t + Math.max(0.06, dur * 0.7));
g.gain.exponentialRampToValueAtTime(0.0001, end);
g.connect(leadBus);
var vibrato = ctx.createOscillator();
var depth = ctx.createGain();
vibrato.frequency.value = 5.2;
depth.gain.setValueAtTime(0, t);
depth.gain.linearRampToValueAtTime(dur > 1 ? 9 : 2, t + 0.45);
vibrato.connect(depth);
vibrato.start(t);
vibrato.stop(end);
[[1, "triangle", 1], [2, "sine", 0.22]].forEach(function (p) {
var o = ctx.createOscillator();
var level = ctx.createGain();
o.type = p[1];
o.frequency.value = hz(midi) * p[0];
level.gain.value = p[2];
depth.connect(o.detune);
o.connect(level);
level.connect(g);
o.start(t);
o.stop(end);
});
}
function kick(t) {
var o = ctx.createOscillator();
var g = ctx.createGain();
o.frequency.setValueAtTime(115, t);
o.frequency.exponentialRampToValueAtTime(44, t + 0.14);
envelope(g.gain, t, 0.004, 0.42, t + 0.26);
o.connect(g);
g.connect(drumBus);
o.start(t);
o.stop(t + 0.3);
}
function shaker(t, level) {
var s = ctx.createBufferSource();
var f = ctx.createBiquadFilter();
var g = ctx.createGain();
s.buffer = shakerBuffer;
f.type = "highpass";
f.frequency.value = 6500;
envelope(g.gain, t, 0.004, level, t + 0.07);
s.connect(f);
f.connect(g);
g.connect(drumBus);
s.start(t);
s.stop(t + 0.09);
}
var pattern = [0, 1, 2, 1, 2, 1, 0, 1];
score.bars.forEach(function (name, b) {
var chord = score.chords[name];
var start = t0 + b * 4 * beat;
var last = b === score.bars.length - 1;
pad(start, 4 * beat, chord.notes);
bass(start, last ? 3.2 : 1.7 * beat, chord.root);
if (!last) {
bass(start + 2.5 * beat, 1.2 * beat, chord.root);
}
for (var e = 0; e < (last ? 1 : 8); e++) {
var t = start + e * beat / 2;
var note = chord.notes[pattern[e]] + (e % 4 === 3 ? 12 : 0);
pluck(t, note, e % 2 ? 0.075 : 0.105);
if (b >= 2 && !last) {
shaker(t, e % 2 ? 0.035 : 0.018);
}
}
if (b >= 2 && !last) {
kick(start);
kick(start + 2 * beat);
}
});
score.melody.forEach(function (n) {
lead(t0 + n[0] * beat, n[1] * beat, n[2]);
});
return master;
}
var ctx = null;
var t0 = 0;
var master = null;
function score() {
return sw.audio.collection.getSongs()[0].score;
}
sw.audio.synth = {
schedule: schedule,
/** Length of the piece in seconds, including the final ring. */
duration: function () {
var s = score();
return s.lengthBeats * 60 / s.bpm + s.tailSeconds;
},
/** Must be called from a user gesture. */
start: function () {
this.stop();
var Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx) {
throw new Error("Web Audio is not available");
}
ctx = new Ctx();
t0 = ctx.currentTime + 0.15;
master = schedule(ctx, ctx.destination, t0, score());
return ctx.resume();
},
pause: function () {
return ctx ? ctx.suspend() : Promise.resolve();
},
resume: function () {
return ctx ? ctx.resume() : Promise.resolve();
},
stop: function () {
if (ctx) {
var closing = ctx;
ctx = null;
master = null;
if (closing.state !== "closed") {
closing.close();
}
}
},
/** Song position in seconds, read from the audio clock. */
time: function () {
if (!ctx) {
return 0;
}
return Math.max(0, ctx.currentTime - t0 - (ctx.outputLatency || 0));
},
context: function () {
return ctx;
},
output: function () {
return master;
}
};
})();
/audio/music/paper-lantern/paper-lantern.js
/* Paper lantern tide: words and music written for the restored animated
* lyrics demo. Released under CC0 with the demo source. The timing, beats and
* score below are read by animated-lyrics.js and song-synth.js. */
(function () {
var BPM = 88;
var beatMs = 60000 / BPM;
function at(bar, beat) {
return Math.round((bar * 4 + (beat || 0)) * beatMs);
}
var lyrics = [
"a paper lantern on the tide",
"carries the evening out to sea",
"i set my small light by its side",
"and let the dark come close to me",
"the harbor hums a quiet tone",
"the ropes keep time against the mast",
"no shore is ever quite alone",
"while one slow lantern drifts on past"
];
var timing = [];
for (var i = 0; i < lyrics.length; i++) {
timing.push([at(2 + i * 2), lyrics[i]]);
}
var beats = [];
for (var b = 0; b <= 80; b++) {
beats.push(Math.round(b * beatMs));
}
var CHORDS = {
Am: {root: 45, notes: [57, 60, 64]},
F: {root: 41, notes: [57, 60, 65]},
C: {root: 48, notes: [55, 60, 64]},
G: {root: 43, notes: [55, 59, 62]},
Dm: {root: 38, notes: [57, 62, 65]},
E: {root: 40, notes: [56, 59, 64]}
};
var bars = ["Am", "F",
"Am", "F", "C", "G", "Am", "F", "Dm", "E",
"F", "C", "G", "Am", "F", "G", "Am", "E",
"Am", "F", "Am"];
// Each phrase: [start beat within the phrase, length in beats, MIDI note]
var phrases = [
[[0, .5, 64], [.5, .5, 69], [1, .5, 69], [1.5, .5, 71], [2, 1, 72], [3, .5, 71], [3.5, .5, 69], [4, 3, 69]],
[[0, .5, 69], [.5, .5, 72], [1, .5, 74], [1.5, 1, 76], [2.5, .5, 74], [3, .5, 72], [3.5, .5, 71], [4, 3, 67]],
[[0, .5, 64], [.5, .5, 69], [1, .5, 69], [1.5, .5, 72], [2, 1, 76], [3, .5, 74], [3.5, .5, 72], [4, 3, 69]],
[[0, .5, 69], [.5, .5, 72], [1, .5, 74], [1.5, 1, 77], [2.5, .5, 76], [3, .5, 74], [3.5, .5, 71], [4, 3, 68]],
[[0, .5, 72], [.5, .5, 72], [1, .5, 74], [1.5, 1, 77], [2.5, .5, 76], [3, .5, 76], [3.5, .5, 74], [4, 3, 72]],
[[0, .5, 71], [.5, .5, 74], [1, .5, 74], [1.5, 1, 79], [2.5, .5, 77], [3, .5, 76], [3.5, .5, 74], [4, 3, 72]],
[[0, .5, 69], [.5, 1, 72], [1.5, .5, 72], [2, .5, 77], [2.5, .5, 76], [3, .5, 74], [3.5, .5, 72], [4, 3, 74]],
[[0, .5, 72], [.5, .5, 71], [1, 1, 69], [2, .5, 72], [2.5, .5, 71], [3, .5, 69], [3.5, .5, 68], [4, 3, 71]]
];
var melody = [];
phrases.forEach(function (phrase, p) {
var start = (2 + p * 2) * 4;
phrase.forEach(function (n) {
melody.push([start + n[0], n[1], n[2]]);
});
});
melody.push([72, 2, 76], [74, 2, 72], [76, 4, 69], [80, 4, 69]);
sw.audio.collection.append({
directory: "music/paper-lantern",
fileName: "paper-lantern",
formats: [],
artist: "written for this restoration",
album: "svg wow demos",
name: "paper lantern tide",
released: "2026",
timingOffset: 0,
lyrics: lyrics,
timing: timing,
beats: beats,
attributions: {
"song": "paper lantern tide",
"words and music": "new for this restoration",
"animation": "vincent hardy, 2009"
},
score: {
bpm: BPM,
chords: CHORDS,
bars: bars,
melody: melody,
// The last chord rings for one bar and a short tail.
lengthBeats: 84,
tailSeconds: 1.6
}
});
})();
/audio/audio-collection.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
sw.audio = sw.audio || {};
/**
* This class provides a simple interface to a collection of songs which can
* then be managed by demos.
*/
sw.audio.Collection = function () {
this.songs = [];
};
sw.audio.Collection.prototype = {
constructor: sw.audio.Collection,
/**
* Appends a new audio to the collection
*
* @param p_song a new song to manage. It should have the following
* properties: directory, formats, artist, album, song, released and
* lyrics.
*/
append : function (p_song) {
this.songs.push(p_song);
},
/**
* @return the list of songs.
*/
getSongs : function () {
return this.songs;
},
/**
* Utility for creating the timing for a given song. Plays the song and
* records 'enter' key presses to determine the timing of the lyrics lines
*
* @param p_songIndex the index of the song to time
*/
buildTiming : function (p_songIndex) {
var start = (new Date()).getTime();
var song = this.songs[p_songIndex];
var curLine = 0;
document.documentElement.addEventListener("click", function () {
var t = (new Date()).getTime() - start;
console.log("[" + t + ", \"" + song.lyrics[curLine++] + "],");
}, false);
}
}
sw.audio.collection = new sw.audio.Collection();/audio/animated-lyrics.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Animated lyrics</title>
<meta name="description" content="Kinetic song lyrics in SVG, timed to an original piece of music synthesized in the browser with Web Audio. Original animation by Vincent Hardy, 2009.">
<style>
html, body { margin: 0; background: #0b0508; color: #f4e9ec; font: 16px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 900px; margin: 0 auto; padding: 16px; }
h1 { font-size: 1.5rem; margin: 0 0 4px; }
p { margin: 0 0 12px; }
a { color: #ffb3c7; }
iframe { display: block; width: 100%; aspect-ratio: 800 / 550; border: 0; background: #000; border-radius: 6px; }
h2 { font-size: 1.05rem; margin: 20px 0 6px; }
.verse { white-space: pre-line; margin: 0; }
</style>
</head>
<body>
<main>
<h1><svg width="22" height="26" viewBox="-13 -18 26 32" aria-hidden="true" fill="none" stroke="#ffd24a" stroke-width="2"><path d="M -8 -9 Q -14 1 -8 11 L 8 11 Q 14 1 8 -9 Z" fill="#ffd24a" fill-opacity=".3"/><path d="M -3 -9 Q -6 1 -3 11 M 3 -9 Q 6 1 3 11 M 0 -9 V -16"/></svg> Animated lyrics</h1>
<p>Animation by Vincent Hardy, 2009. <a href="/gallery/animated-lyrics/">Gallery page</a></p>
<iframe src="animated-lyrics.svg" title="Animated lyrics demo. Click inside to start the song. Space plays or pauses, S stops, L shows the lyrics." allow="autoplay"></iframe>
<h2>Paper lantern tide</h2>
<p class="verse">a paper lantern on the tide
carries the evening out to sea
i set my small light by its side
and let the dark come close to me
the harbor hums a quiet tone
the ropes keep time against the mast
no shore is ever quite alone
while one slow lantern drifts on past</p>
<p>Words and music were written for this restoration and are played by a synthesizer running in your browser. Sound starts only after you click.</p>
</main>
</body>
</html>