Graffitis
Replays Graffiti Markup Language tags as SVG strokes with canvas spray, and records tags you draw.
What you are seeing
A white control card above a dark drawing area. A thick white tag with a black outline paints itself stroke by stroke, reading SVG Wow, with fine white spray bursting from the moving tip. Controls choose other tags, record a new one, show its SVG or GML source, or display it in gold on a brick wall.
How it works
GML stores a tag as strokes of timed points. The demo smooths each stroke into cubic curves and builds an SVG path.
Setting the dash and gap to the path length, then animating the dash offset, makes each stroke appear to be painted.
A canvas under the strokes adds fading particles that follow the speed of the pen.
The record mode captures pointer input as new GML, and the panels show it as SVG, as GML or through a brick wall filter.
History
Posted on September 6, 2010. It loaded tags from a public GML repository that this version no longer contacts.
Source
/graffitis/graffitis.xhtml
<!-- ======================================================================= -->
<!-- Vincent Hardy -->
<!-- License terms: see svg-wow.org -->
<!-- CC0 http://creativecommons.org/publicdomain/zero/1.0/ -->
<!-- ======================================================================= -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SVG graffitis: replaying recorded strokes</title>
<meta name="description" content="Replays Graffiti Markup Language tags as animated SVG strokes with canvas spray particles, and records new tags drawn with a mouse or touch."/>
<link rel="icon" href="../res/2.0/images/favicon.svg" />
<link rel="icon alternate" href="../res/2.0/images/favicon.png" />
<link rel="stylesheet" type="text/css" href="graffitis.css" title="defaultStyle"/>
</head>
<body>
<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>
<script type="text/javascript" src="graffitis.js"></script>
<!-- SVG background -->
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="100%" height="100%" id="backgroundSVG">
<defs>
<linearGradient id="colored-background" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" style="stop-color:#a0a0a0;stop-opacity:1"/>
<stop offset="1" style="stop-color:#f0f0f0;stop-opacity:1"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="#f0f0f0"/>
<rect width="100%" height="400px" fill="url(#colored-background)"/>
</svg>
<div id="content">
<div id="svg-capture">
<span id="close-capture">x</span>
<h2>SVG Export</h2>
<div id="instructions">Double click on the SVG source below to select it.</div>
<div id="svg-text"></div>
</div> <!-- svg-capture -->
<div id="gml-capture">
<span id="close-gml-capture">x</span>
<h2>GML Source</h2>
<div id="gml-text"></div>
</div> <!-- gml-capture -->
<div id="brick-overlay">
<span id="close-overlay">x</span>
<svg width="100%" height="100%" viewBox="0 0 600 400"
xmlns="http://www.w3.org/2000/svg"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<filter id="overlay" filterUnits="userSpaceOnUse" x="0" y="0" width="600" height="400">
<feImage xlink:href="bricks.png"
result="texture"/>
<feColorMatrix type="luminanceToAlpha" result="screenMask"/>
<feComponentTransfer result="multiplyMask">
<feFuncA type="linear" slope="-1" intercept="1"/>
</feComponentTransfer>
<feBlend mode="screen" in="texture" in2="SourceGraphic" result="screen"/>
<feBlend mode="multiply" in="texture" in2="SourceGraphic" result="multiply"/>
<feComposite operator="in" in="screen" in2="screenMask" result="maskedScreen"/>
<feComposite operator="in" in="multiply" in2="multiplyMask" result="maskedMultiply"/>
<feComposite operator="arithmetic" in="maskedScreen" in2="maskedMultiply"
k1="0" k2="1" k3="1" k4="0" />
</filter>
</defs>
<g font-weight="normal" text-anchor="middle" filter="url(#overlay)" stroke="black" stroke-width="22" fill="none">
<g id="stroke-paths"></g>
<use xlink:href="#stroke-paths" stroke="gold" stroke-width="16"/>
</g>
</svg>
</div>
<div id="header">
<h1>SVG Graffitis</h1>
<div id="config" style="cursor:pointer">
<div id="actions">
<span class="list-label">Actions:</span>
<ul id="actions" class="inline-list">
<li id="record" >record</li>
<li id="play" style="display:none">play</li>
<li id="to-svg" >show SVG</li>
<li id="show-gml" >show GML</li>
<li id="show-brick-overlay" >show brick overlay</li>
</ul>
</div> <!-- actions -->
<div id="on-blackbook">
<span id="suggestions" class="list-label">Sample tags:</span>
<ul id="predefined" class="inline-list">
<li id="161">spiral</li>
<li id="12526">wave</li>
<li id="random">random</li>
</ul>
</div> <!-- on-blackbook -->
<div id="local">
<span class="list-label">Local:</span>
<ul id="predefinedLocal" class="inline-list">
<li id="json/svgwow.js">svg wow</li>
<li id="json/paris.js">paris</li>
<li id="last-recorded">last recorded</li>
</ul>
</div> <!-- local -->
<div id="spray-paint-control">
<input type="checkbox" id="show-particles"></input>
<span class="label">spray paint</span>
</div> <!-- spray-paint-control -->
</div>
</div>
<svg id="graffitiViewer" xmlns="http://www.w3.org/2000/svg" version="1.1"
viewBox="0 0 600 400"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="600px" height="400px">
<desc>A dark drawing area where a graffiti tag is painted stroke by stroke as thick white lines with black outlines, with small spray particles coming off the moving tip.</desc>
<defs>
<radialGradient id="background" cx="0.2" cy="0.3" r="0.8" gradientUnits="objectBoundingBox">
<stop offset="0" stop-color="black" />
<stop offset="1" stop-color="#404040" />
</radialGradient>
</defs>
<rect width="100%" height="100%" fill="url(#background)" rx="5" ry="5"/>
<svg:foreignObject
x="0" y="0" width="100%" height="100%"
xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/1999/xhtml">
<canvas id="graffitis-canvas" style="display:none;" width="600" height="400"/>
</svg:foreignObject>
<g id="graffiti" class="stroke"/>
</svg>
<p id="tag-source">Tags use Graffiti Markup Language (GML). "svg wow" and "paris" were recorded with this demo; "spiral" and "wave" are generated for this restoration.</p>
<p id="demo-status" role="status"></p>
</div>
</body>
</html>
/graffitis/graffitis.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
function onReady(Y) {
// =========================================================================
// Graffiti renderers.
//
// Renderers are called as the graffiti is drawn. They can render when a
// point is updated (the update method), skipped (the skipPoint method)
// or after all the graffiti has been drawn (the fadeRendering method).
// =========================================================================
var StrokeDashAnimation = {
initialize : function (state) {
var paths = state.paths, n = paths.length;
for (var si = 0; si < n; si++) {
paths[si].setAttribute("stroke-dasharray",
paths[si]._pathLength + ',' +
paths[si]._pathLength * 2);
paths[si].setAttribute('stroke-dashoffset',
paths[si]._pathLength * 1.5);
this._paths = paths;
}
},
update : function (curStroke, curPoint, progress) {
this._paths[curStroke].setAttribute("stroke-dashoffset",
this._paths[curStroke]._pathLength * (1 - progress));
},
skipPoint : function (point, curStroke) {
// Do nothing. See update method.
},
fadeRendering : function () {
return false; // Nothing to render after the end of the animation.
}
};
var ParticlesAnimation = {
initialize : function (state) {
this._state = state;
this._particles = [];
},
update : function (curStroke, curPoint, progress) {
this.fadeParticles(this._particles);
},
skipPoint : function (point, curStroke) {
this.addPointParticles(point,
this._state.matrix,
this._state.origin,
this._particles);
},
fadeRendering: function () {
var particles = this._particles, hasMore = true;
if (particles.length === 0) {
hasMore = false;
} else {
this.fadeParticles(particles);
}
return hasMore;
},
/**
* Draws the particles at their current position.
*/
fadeParticles: function (particles) {
var nParticles = particles.length,
particle,
decel;
for (var pi = nParticles - 1; pi >= 0; pi--) {
particle = particles[pi];
decel = (particle.maxIter - particle.i) / particle.maxIter;
particle.i++;
particle.x += decel * particle.dx;
particle.y += decel * particle.dy;
ctx.globalAlpha = (particle.maxIter - particle.i) / particle.maxIter;
ctx.fillRect(particle.x, particle.y, particle.size, particle.size);
if (particle.i >= particle.maxIter) {
particles.splice(pi, 1);
}
}
},
/**
* Adds particles to the particles array for the given point.
*
* @param point the point for which particles should be added.
* @param matrix the transform between the graffiti's coordinate system
* and the SVG coordinate system.
* @param origin the graffiti's origin in the SVG coordinate system.
* @param particles the array of particles to append to.
*/
addPointParticles: function (point, matrix, origin, particles) {
var speed = {
x: point.speedOut.sx,
y: point.speedOut.sy
},
s = {},
pt = {};
matrix.transformPoint(point, pt);
// Transform the speed vector in the target coordinate system
// We transform the vector ({0,0}, {speed.x, speed.y}) and
// compute its x and y axis values.
matrix.transformPoint(speed, s);
speed = {
x: s.x - origin.x,
y: s.y - origin.y
};
// Convert the speed to polar coordinates
var theta = Math.atan2(speed.y, speed.x),
delta = Math.PI / 10,
alpha,
r = Math.sqrt(speed.x * speed.x +
speed.y * speed.y),
rad;
var nP = Math.round(MIN_PARTICLES + DELTA_PARTICLES * Math.random());
for (var pi = 0; pi < nP; pi++) {
alpha = theta + delta * (1 - 2 * Math.random());
rad = r * (0.8 + 0.8 * Math.random());
particles.push({
x: pt.x,
y: pt.y,
dx: rad * Math.cos(alpha) * animationRateSec,
dy: rad * Math.sin(alpha) * animationRateSec,
i: 1,
maxIter: PARTICLE_ITERATIONS,
size: PARTICLE_SIZE
});
}
}
};
/**
* PatchRenderingAnimation is an ugly hack to make up for a bug found in
* Safari 5.0, Firefox 3.6 and Chrome with line joins which get 'cut-off'
* and create a nasty rendering result.
*/
var PatchRenderingAnimation = {
_state: null,
initialize: function (state) {
this._state = state;
},
update : function (curStroke, curPoint, progress) {
},
skipPoint : function (point, curStroke) {
var pt = this._state.matrix.transformPoint(point),
outerPatchId = "#stroke_" + curStroke + "_outerPatch",
innerPatchId = "#stroke_" + curStroke + "_innerPatch";
Y.one(outerPatchId).loadContent({
tag: 'circle',
cx: pt.x,
cy: pt.y,
r: OUTER_WIDTH / 2,
fill: 'black',
stroke: 'none'
});
Y.one(innerPatchId).loadContent({
tag: 'circle',
cx: pt.x,
cy: pt.y,
r: INNER_WIDTH / 2,
fill: 'white',
stroke: 'none'
});
},
fadeRendering : function () {
return false;
}
};
var MultiplexAnimations = {
animations: [StrokeDashAnimation, ParticlesAnimation, PatchRenderingAnimation],
initialize: function (state) {
for (var i = 0; i < this.animations.length; i++) {
this.animations[i].initialize(state);
}
},
update: function (curStroke, curPoint, progress) {
for (var i = 0; i < this.animations.length; i++) {
this.animations[i].update(curStroke, curPoint, progress);
}
},
fadeRendering : function () {
var result = false;
for (var i = 0; i < this.animations.length; i++) {
result = this.animations[i].fadeRendering() || result;
}
return result;
},
skipPoint : function (point, curStroke) {
for (var i = 0; i < this.animations.length; i++) {
this.animations[i].skipPoint(point, curStroke);
}
}
};
// =========================================================================
// Configuration parameters
// =========================================================================
/**
* The minimum and delta number of particles per graffiti point
*/
var MIN_PARTICLES = 20,
DELTA_PARTICLES = 20,
/**
* The number of iterations before a particle stops
*/
PARTICLE_ITERATIONS = 15,
/**
* Margin around the graffiti
*/
MARGIN = 100,
/**
* Size of the particle rectangles
*/
PARTICLE_SIZE = 1,
/**
* Color used to draw particles
*/
PARTICLE_COLOR = 'white',
/**
* Color used to record graffitis
*/
RECORD_COLOR = 'crimson',
/**
* Size used for record markers
*/
RECORD_MARKER_SIZE = 3;
/**
* Default renderer
*/
DEFAULT_RENDERER = MultiplexAnimations,
/**
* Stroke widths, inner and outer
*/
INNER_WIDTH = 14,
OUTER_WIDTH = 18,
// =========================================================================
// Misc scope variables, used accross graffitis
// =========================================================================
/**
* The group holding the SVG graffiti
*/
g = Y.one("#graffiti"),
/**
* Particles canvas.
*/
canvas = Y.one('#graffitis-canvas'),
ctx = Y.Node.getDOMNode(canvas).getContext('2d'),
/**
* The target size for the graffiti.
*/
targetWidth = g.get('nearestViewportElement').get('width') - MARGIN,
targetHeight = g.get('nearestViewportElement').get('height') - MARGIN,
/**
* The delay between animation frames.
*/
animationRate = 20,
animationRateSec = 20 / 1000,
/**
* Recorder: used to record a graffiti
*/
recorder = null;
/**
* The current graffiti renderer
*/
renderer = DEFAULT_RENDERER;
// =========================================================================
// Graffiti state
// =========================================================================
var graffitiState = {
/**
* The current GML result
*/
gmlResult: null
};
// =========================================================================
// Animation state
// =========================================================================
var animationState = {
/**
* Currently painted stroke
*/
curStroke: 0,
/**
* End of the current segment on the current stroke.
*/
curPoint: 0,
/**
* Current setInterval id
*/
intervalId: -1
};
/**
* There are different ways to specify the rotation angle in GML. This
* takes care of the differences between versions.
*/
function extractRotation (gmlResult) {
var rotation = 0, env = gmlResult.gmlData.gml.tag.environment, up;
if (env !== undefined) {
if (env.up !== undefined) {
up = env.up;
}
if (up !== undefined) {
rotation = -90 + Math.atan2(up.y, up.x) * 180 / Math.PI;
}
}
return rotation;
}
/**
* Computes the transform matrix for the given graffiti.
* @param glmResult
* @return the transform from graffiti space to the SVG space.
*/
function computeGraffitiTransform (gmlResult) {
var bbox = gmlResult.gmlMetrics.bounds,
sx = 1, sy = 1, s = 1, rotation = 0,
env = gmlResult.gmlData.gml.tag.environment;
// Compute the scale factor for the graffiti: use the targetWidth and height
// and the bounding box of the computed graffiti bounds.
if (bbox.width > 0) {
sx = targetWidth / bbox.width;
}
if (bbox.height > 0) {
sy = targetHeight / bbox.height;
}
s = sx;
if (sy < sx) {
s = sy;
}
// Compute the aspect ratio based on the environment's width and height
var ar = 1;
if (env.screen_bounds !== undefined) {
ar = env.screen_bounds.x / env.screen_bounds.y;
}
// Compute the rotation from the gmlData.
rotation = extractRotation(gmlResult);
var matrix = new Y.DOM.Matrix();
matrix.translate(((MARGIN + targetWidth) / 2),
((MARGIN + targetHeight) / 2));
matrix.rotate(rotation);
matrix.scaleNonUniform(s, s * ar);
matrix.translate((-bbox.x - bbox.width / 2),
(-bbox.y - bbox.height / 2));
return matrix;
}
/**
* Used to lower the decimal precision on path data.
*/
function round (v) {
return Math.round(v * 10000) / 10000;
}
/**
* Creates the graffiti shapes as SVG path elements.
*
* @param gmlResult
* @return an array of path elements.
*/
function createGraffitiPaths (gmlResult) {
var strokes = gmlResult.gmlMetrics.strokes,
nStrokes = strokes.length,
points,
segments,
nSegments,
matrix,
seg,
d,
paths = [],
strokeCounter = 0,
pathLength = 0;
matrix = computeGraffitiTransform(gmlResult);
for (var si = 0; si < nStrokes; si++) {
points = strokes[si].pt;
segments = smooth(points, 0.75);
nSegments = segments.length;
d = "";
segments[0][0] = matrix.transformPoint(segments[0][0]);
if (nSegments > 0) {
d = "M" + round(segments[0][0].x) + "," +
round(segments[0][0].y);
}
for (var i = 0; i < nSegments; i++) {
seg = segments[i];
seg[1] = matrix.transformPoint(seg[1]);
seg[2] = matrix.transformPoint(seg[2]);
seg[3] = matrix.transformPoint(seg[3]);
d = d.concat("C", round(seg[1].x), ",", round(seg[1].y), " ",
round(seg[2].x), ",", round(seg[2].y), " ",
round(seg[3].x), ",", round(seg[3].y));
}
g.loadContent({
tag: 'g',
id: "stroke_" + strokeCounter + "_outerPatch"
});
g.loadContent({
tag: "path",
id: "stroke_" + strokeCounter,
d: d
});
paths.push(g.get('lastChild'));
paths[si]._pathLength = Y.Node.getDOMNode(paths[si]).getTotalLength();
pathLength += paths[si]._pathLength;
g.loadContent({
tag: 'g',
id: "stroke_" + strokeCounter + "_innerPatch"
});
g.loadContent({
tag: "use",
"xlink:href": "#stroke_" + strokeCounter,
'class': 'inner-stroke'
});
strokeCounter++;
}
return paths;
}
/**
* Exports the current graffiti to SVG
*/
function exportToSVG () {
if (graffitiState.paths !== undefined) {
// Create a simple SVG file with the path data.
var svg = Y.one('#graffitiViewer'),
bounds = svg._node.getBoundingClientRect(),
width = Math.round(bounds.right - bounds.left),
height = Math.round(bounds.bottom - bounds.top),
paths = graffitiState.paths, n = paths.length,
Animate = sw.animation.Animate, Easing = Y.Easing;
var svgContent = [
"<svg width='", width, "' ",
"height='", height + "' ",
"xmlns='", Y.svgNS + "' ",
"stroke='black' fill='none' stroke-width='" +
OUTER_WIDTH + "' ",
"stroke-linecap='round' stroke-linejoin='round' ",
"viewBox='0 0 ", width, ' ', height, "'>\n"];
for (var i = 0; i < n; i++) {
svgContent.push("<path d='");
svgContent.push(paths[i]._node.getAttribute('d'));
svgContent.push("' />\n");
}
svgContent.push("</svg>");
Y.one('#svg-text').set('textContent', svgContent.join(''));
// Animate showing the svg content in a dialog.
var headerBounds = Y.one('#header')._node.getBoundingClientRect(),
svgCapture = Y.one('#svg-capture').setStyle('display', 'block'),
captureBounds = svgCapture._node.getBoundingClientRect(),
captureWidth = captureBounds.right - captureBounds.left,
headerWidth = headerBounds.right - headerBounds.left;
svgCapture.setStyle('left', headerBounds.left +
(headerWidth - captureWidth) / 2);
var showSVGCapture = new Animate({
node: svgCapture,
from: {
top: -captureBounds.height
},
to: {
top: "50px"
},
duration: 2,
easing: Easing.elasticOut
});
showSVGCapture.run();
}
}
/**
* Show the current graffiti's GML
*/
function showGML () {
if (graffitiState.paths !== undefined) {
// Create a simple SVG file with the path data.
var Animate = sw.animation.Animate, Easing = Y.Easing;
if (graffitiState.gmlResult !== undefined) {
var gmlContent = JSON.stringify(graffitiState.gmlResult.gmlData);
Y.one('#gml-text').set('textContent', gmlContent);
// Animate showing the svg content in a dialog.
var headerBounds = Y.one('#header')._node.getBoundingClientRect(),
gmlCapture = Y.one('#gml-capture').setStyle('display', 'block'),
captureBounds = gmlCapture._node.getBoundingClientRect(),
captureWidth = captureBounds.right - captureBounds.left,
headerWidth = headerBounds.right - headerBounds.left;
gmlCapture.setStyle('left', headerBounds.left +
(headerWidth - captureWidth) / 2);
var showSVGCapture = new Animate({
node: gmlCapture,
from: {
top: -captureBounds.height
},
to: {
top: "50px"
},
duration: 2,
easing: Easing.elasticOut
});
showSVGCapture.run();
} else {
alert("There is no graffiti displayed yet. Display one before" +
" showing its GML source");
}
}
}
/**
* Shows the current graffiti in the overlay panel, demonstrating a
* sophisticated filter effect.
*/
function showOverlay () {
if (graffitiState.paths === undefined) {
setStatus('Show a tag first, then open the brick overlay.');
return;
}
var headerBounds = Y.one('#header')._node.getBoundingClientRect(),
brickOverlay = Y.one('#brick-overlay').setStyle('display', 'block'),
overlayBounds = brickOverlay._node.getBoundingClientRect(),
overlayWidth = overlayBounds.right - overlayBounds.left,
headerWidth = headerBounds.right - headerBounds.left;
brickOverlay.setStyle('left', headerBounds.left +
(headerWidth - overlayWidth) / 2);
var showSVGCapture = new sw.animation.Animate({
node: brickOverlay,
from: {
top: -overlayBounds.height
},
to: {
top: "50px"
},
duration: 2,
easing: Y.Easing.elasticOut
});
showSVGCapture.run();
// Show the current strokes in the overlay content.
var overlayContent = Y.one('#stroke-paths'),
paths = graffitiState.paths, n = paths.length;
overlayContent.removeAllChildren();
for (var i = 0; i < n; i++) {
overlayContent.loadContent({
tag: 'path',
d: paths[i].getAttribute('d')
});
}
}
/**
* The main animation method.
*
*/
function animateStroke () {
var curTime = (new Date()).getTime(),
elapsed = (curTime - animationState.startTime) / 1000, // ms to s
progress,
point, prevPoint,
segmentProgress,
allStrokesConsumed = false,
curStroke = animationState.curStroke,
curPoint = animationState.curPoint,
strokesInfo = animationState.strokesInfo,
gmlResult = graffitiState.gmlResult,
points,
paths = graffitiState.paths;
// Find out which stroke we are animating.
while (strokesInfo[curStroke].tagEndTimeOffset < elapsed) {
// We are past the duration of the current stroke.
// Skip all the remaining points on the stroke.
points = strokesInfo[curStroke].points;
for (var i = curPoint; i < points.length - 1; i++) {
renderer.skipPoint(points[i], curStroke);
}
// Make sure the current stroke's dashoffset is properly set.
paths[curStroke].removeAttribute('stroke-dashoffset');
paths[curStroke].removeAttribute('stroke-dasharray');
curStroke++;
curPoint = 0;
if (curStroke === gmlResult.gmlMetrics.strokes.length) {
// We reached the end of the last stroke. Stop the animation
// now.
clearInterval(animationState.intervalId);
// Let the renderers finish their rendering.
animationState.intervalId = setInterval(fadeRendering, animationRate);
startTime = (new Date()).getTime()
allStrokesConsumed = true;
break;
}
}
if (allStrokesConsumed === false) {
points = strokesInfo[curStroke].points;
// Find out which stroke point we are on.
while (curPoint < points.length - 1 &&
points[curPoint].tagTimeOffset < elapsed) {
renderer.skipPoint(points[curPoint], curStroke);
curPoint++;
// Can we have reached the end of the current stroke?
// No because we checked that we did not go beyond the end of
// the stroke right before.
}
// We are in the segment ending on 'point'. Compute the
// penetration in the current segment and then the current
// position.
if (curPoint > 0) {
point = points[curPoint];
prevPoint = points[curPoint - 1];
// Two recorded points can share a timestamp.
segmentProgress = point.tagTimeOffset > prevPoint.tagTimeOffset ?
Math.min(1, (elapsed - prevPoint.tagTimeOffset) /
(point.tagTimeOffset - prevPoint.tagTimeOffset)) : 1;
progress = (prevPoint.strokeAdvance +
segmentProgress *
(point.strokeAdvance - prevPoint.strokeAdvance)) /
strokesInfo[curStroke].strokeLength;
} else {
progress = 0;
}
animationState.curPoint = curPoint;
animationState.curStroke = curStroke;
renderer.update(curStroke, curPoint, progress);
}
}
/**
* Animation function after the graffiti has been drawn but rendering may
* not be complete. The rendering will stop when the rendering is complete.
*/
function fadeRendering () {
if (renderer.fadeRendering() === false) {
clearInterval(animationState.intervalId);
animationState.intervalId = -1;
}
}
/**
* Called to initiate a recording a new graffiti drawing.
*/
function record () {
if (recorder !== null) {
recorder.stop();
}
setStatus('Recording: drag in the dark area to draw, then choose play.');
// If there is a pending animation, stop it now.
if (animationState.intervalId !== -1) {
clearInterval(animationState.intervalId);
animationState.intervalId = -1;
}
// Show the play button, hid the record button
Y.one("#play").setStyle('display', 'inline');
Y.one('#record').setStyle('display', 'none');
// Make sure the canvas is displayed
canvas.setStyle('display', 'block');
// Remove any existing graffiti
g.removeAllChildren();
// Now, clear the canvas for recording.
ctx.clearRect(0, 0, canvas.get('width'), canvas.get('height'));
ctx.globalAlpha = 1;
ctx.fillStyle = RECORD_COLOR;
// Instantiate a new GraffitiRecorder to record a new graffiti.
recorder = new sw.GraffitiRecorder(Y.one('#graffitiViewer'));
recorder.on(recorder.events.newPoint, function (event) {
ctx.fillRect(event.x, event.y,
RECORD_MARKER_SIZE,
RECORD_MARKER_SIZE);
});
}
/**
* Called when the graffiti has been retrieved and pre-processed.
*
* @param gmlResult the GML data that was loaded and processed by the
* GraffitiLib
*/
function onGMLLoaded (gmlResult) {
var matrix = computeGraffitiTransform(gmlResult);
// Reset state
g.removeAllChildren();
if (animationState.intervalId !== -1) {
clearInterval(animationState.intervalId);
}
ctx.globalAlpha = 1;
ctx.clearRect(0, 0, canvas.get('width'), canvas.get('height'));
ctx.fillStyle = PARTICLE_COLOR;
ctx.lineSize = 0.5;
ctx.strokeStyle = PARTICLE_COLOR;
animationState = {
curStroke: 0,
curPoint: 0,
strokesInfo: gmlResult.gmlMetrics.strokesInfo,
// With reduced motion the tag is drawn complete on the first frame.
startTime: (new Date()).getTime() -
(SwRestore.reducedMotion() ? 3600000 : 0),
intervalId: -1
};
graffitiState = {
matrix: matrix,
origin: matrix.transformPoint({
x: 0,
y: 0
}),
gmlResult: gmlResult,
paths: createGraffitiPaths(gmlResult)
};
// Check whether or not we should be showing the canvas
canvas.setStyle('display',
Y.one('#show-particles').get('checked') === true ? 'block': 'none');
renderer.initialize(graffitiState);
animationState.intervalId = setInterval(animateStroke, animationRate);
}
function setStatus (message) {
Y.one('#demo-status').set('textContent', message);
}
function requestGML(graffitiId) {
var gmlLib = new sw.graffiti.GraffitiLib();
gmlLib.on(gmlLib.events.gmlLoaded, onGMLLoaded);
gmlLib.request(graffitiId);
}
function requestGMLLocal(graffitiURL) {
var gmlLib = new sw.graffiti.GraffitiLib();
gmlLib.on(gmlLib.events.gmlLoaded, onGMLLoaded);
gmlLib.requestLocal(graffitiURL);
}
function showStrokeSkeleton () {
var strokeSkeleton = Y.one("#stroke-skeleton");
if (strokeSkeleton !== undefined && strokeSkeleton !== null) {
if (strokeSkeleton.getStyle("display") === "none") {
strokeSkeleton.setStyle("display", "inline");
} else {
strokeSkeleton.setStyle("display", "none");
}
}
}
// Initialize form event listeners
/**
* When we click on a predefined graffiti id, we automatically fetch it.
*/
Y.one("#predefined").on('click', function (event) {
var id = event.target.get('id');
if (id === '161' || id === '12526') {
requestGML(id);
}
});
Y.one("#predefinedLocal").on('click', function (event) {
var id = event.target.get('id');
if (id.indexOf('json/') === 0) {
requestGMLLocal(id);
}
});
Y.one("#random").on('click', function (event) {
var tags = ['json/svgwow.js', 'json/paris.js', 'json/spiral.js', 'json/wave.js'];
requestGMLLocal(tags[Math.floor(Math.random() * tags.length)]);
});
Y.one("#record").on('click', function (event) {
record();
});
function playLastRecorded () {
if (recorder === null || !recorder.hasStrokes()) {
setStatus('Nothing recorded yet. Choose record, then drag in the dark area.');
} else {
recorder.stop();
setStatus('');
Y.one("#play").setStyle("display", "none");
Y.one("#record").setStyle("display", "inline");
var gmlLib = new sw.graffiti.GraffitiLib();
gmlLib.on(gmlLib.events.gmlLoaded, onGMLLoaded);
gmlLib.onGraffitiLoad(recorder.getGMLRecord(), "record");
}
}
Y.one("#play").on('click', playLastRecorded);
Y.one("#last-recorded").on('click', playLastRecorded);
Y.one('#to-svg').on('click', exportToSVG);
Y.one('#show-gml').on('click', showGML);
Y.one('#show-brick-overlay').on('click', showOverlay);
Y.one('#close-capture').on('click', function () {
var svgCapture = Y.one('#svg-capture'),
captureBounds = svgCapture._node.getBoundingClientRect(),
hideSVGCapture = new sw.animation.Animate({
node: svgCapture,
from: {
top: "50px"
},
to: {
top: (captureBounds.top - captureBounds.bottom) + "px"
},
duration: 0.5,
easing: Y.Easing.backIn
});
hideSVGCapture.onEnd(function () {
svgCapture.setStyle('display', 'none');
});
hideSVGCapture.run();
});
Y.one('#close-gml-capture').on('click', function () {
var gmlCapture = Y.one('#gml-capture'),
captureBounds = gmlCapture._node.getBoundingClientRect(),
hideGMLCapture = new sw.animation.Animate({
node: gmlCapture,
from: {
top: "50px"
},
to: {
top: (captureBounds.top - captureBounds.bottom) + "px"
},
duration: 0.5,
easing: Y.Easing.backIn
});
hideGMLCapture.onEnd(function () {
gmlCapture.setStyle('display', 'none');
});
hideGMLCapture.run();
});
Y.one('#close-overlay').on('click', function () {
var brickOverlay = Y.one('#brick-overlay'),
overlayBounds = brickOverlay._node.getBoundingClientRect(),
hideOverlay = new sw.animation.Animate({
node: brickOverlay,
from: {
top: "50px"
},
to: {
top: (overlayBounds.top - overlayBounds.bottom) + "px"
},
duration: 0.5,
easing: Y.Easing.backIn
});
hideOverlay.onEnd(function () {
brickOverlay.setStyle('display', 'none');
});
hideOverlay.run();
});
Y.one("#show-particles").on('click', function (evt) {
var displayValue = 'none';
if (evt.target.get('checked') === true) {
displayValue = "block";
}
Y.one("#graffitis-canvas").setStyle('display', displayValue);
});
// Initialize default UI state.
Y.one('#show-particles')._node.checked = !SwRestore.reducedMotion();
// Keyboard access for the action lists.
Y.all('#config li').each(function (item) {
var node = item._node;
node.setAttribute('tabindex', '0');
node.setAttribute('role', 'button');
node.addEventListener('keydown', function (evt) {
if (evt.key === 'Enter' || evt.key === ' ') {
evt.preventDefault();
node.click();
}
});
});
// Show a tag on load so the viewer is never an empty panel.
requestGMLLocal('json/svgwow.js');
}
/**
* Main entry point. Refer to the YUI documentation to understand how the
* YUI framework loads scripts and handles dependencies.
*
* The following declares the modules required by the code (such as
* 'anim-svg') and their dependencies.
*
* The onScriptsReady function is called when the DOM tree is ready.
*/
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']
}
}
},
demo: {
base: "./",
modules: {
'graffiti-lib': {
path: 'graffiti-lib.js',
requires: ['node']
},
'graffitis-record': {
path: 'graffitis-record.js',
requires: ['node', 'event-custom']
},
'smooth': {
path: 'smooth.js'
}
}
}
},
filter: 'debug'
}).use('dom-svg', 'node-svg', 'dom-style-svg', 'anim-svg', 'anim-timing',
'graffiti-lib', 'smooth', 'graffitis-record', function(YUI) {
YUI.on('contentready', function () {
onReady(YUI);
}, 'body');
});/graffitis/graffitis.css
html {
background-color: #a0a0a0;
width: 100%;
min-height: 100%;
overflow-x: hidden;
}
body {
padding: 0px;
margin: 0px;
width: 100%;
min-height: 100%;
}
#backgroundSVG {
position: absolute;
z-index: -1;
top: 0px;
}
#graffitiViewer {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
background: none;
border-radius: 5px;
margin-left: auto;
margin-right: auto;
display: block;
margin-top: auto;
margin-bottom: auto;
-moz-box-shadow:0 0 10px rgba(0,0,0,0.5);
-webkit-box-shadow:0 0 10px rgba(0,0,0,0.5);
box-shadow:0 0 10px rgba(0,0,0,0.5);
width: 600px;
max-width: 100%;
height: auto;
aspect-ratio: 3 / 2;
box-sizing: border-box;
border: 1px solid rgba(255,0,0,0);
}
#tag-source, #demo-status {
width: 600px;
max-width: calc(100% - 20px);
margin-left: auto;
margin-right: auto;
margin-top: 0.5em;
display: block;
color: #505050;
font-family: Tahoma, Verdana, system-ui, sans-serif;
font-weight: bold;
font-size: 12px;
text-shadow: 1px 1px 1px rgba(255,255,255,0.8), -1px -1px 1px rgba(0,0,0,0.2);
text-decoration: none;
}
#tag-source a {
color: #303030;
}
#tag-source a:hover {
color: crimson;
}
#svg-capture, #brick-overlay, #gml-capture {
z-index: 2;
border: 1px solid #a0a0a0;
background-color: rgba(255,255,255,0.95);
color: #303030;
width: 540px;
max-width: calc(100vw - 40px);
padding: 10px;
display: block;
margin-left: auto;
margin-right: auto;
position: absolute;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0,0,0,0.5);
-moz-box-shadow:0 0 5px rgba(0,0,0,0.5);
-webkit-box-shadow:0 0 5px rgba(0,0,0,0.5);
top: 0px;
top: -600px;
max-height: 550px;
}
#brick-overlay > svg {
width: 520px;
max-width: 100%;
height: auto;
aspect-ratio: 3 / 2;
}
#close-capture, #close-overlay, #close-gml-capture {
position: absolute;
top: 3px;
left: 3px;
border: 1px solid #d0d0d0;
color: #d0d0d0;
background: white;
z-index: 3;
padding-left: 3px;
padding-right: 3px;
font-family: monospace;
font-size: 12px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
cursor: pointer;
}
#close-capture:hover, #close-overlay:hover {
color: crimson;
border: 1px solid crimson;
}
#svg-capture h2, #gml-capture h2 {
font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
font-size: 50px;
color: black;
padding-top: 0px;
padding-bottom: 0px;
margin-top: 20px;
margin-bottom: 0px;
}
#instructions {
font-size: 11px;
}
#svg-text, #gml-text {
padding: 10px;
font-family: monospace;
font-size: 11px;
font-weight: bold;
color: #808080;
height: 350px;
overflow: auto;
border: 1px solid #e0e0e0;
}
#header {
position: relative;
width: 580px;
max-width: calc(100% - 20px);
box-sizing: border-box;
padding: 10px;
margin-top: 20px;
margin-bottom: 20px;
font-family: Tahoma, Verdana, system-ui, sans-serif;
font-size: 12px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
background: white;
border-radius: 5px;
margin-left: auto;
margin-right: auto;
display: block;
-moz-box-shadow:0 0 5px rgba(0,0,0,0.5);
-webkit-box-shadow:0 0 5px rgba(0,0,0,0.5);
box-shadow:0 0 5px rgba(0,0,0,0.5);
color: black;
}
#header h1 {
font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
font-size: clamp(36px, 11vw, 64px);
margin: 0px;
text-align: center;
color: white;
text-shadow: 0px 0px 5px rgba(0,0,0,0.5), 1px 1px 3px rgba(0,0,0,0.5);
}
#header a {
color: #808080;
text-decoration: none;
text-shadow: 0px 0px 2px rgba(0,0,0,0.5);
padding-left: 10px;
}
#header a:hover {
color: crimson;
}
#header hr {
border: none;
border-top: 1px solid #e0e0e0;
margin-bottom: 1em;
}
#showSkeleton {
width: auto;
display: inline-block;
color: white;
font-family: Tahoma, Verdana, system-ui, sans-serif;
font-weight: normal;
font-size: 12px;
cursor: pointer;
border: 1px solid gray;
padding: 5px;
}
#showSkeleton:hover {
fill: crimson;
fill-opacity: 1;
}
#graffitiId {
margin-left: 2ex;
}
#config {
color: #a0a0a0;
}
#config p {
display: inline-block;
}
#config > div {
display: block;
padding: 5px;
margin: 0px;
}
#config > div > span {
min-width: 14ex;
display: inline-block;
text-align: right;
}
.buttons {
width: 100%;
}
.button:after {
content: none;
}
#replicate {
}
.inline-list {
display: inline;
margin: 5px;
margin-bottom: 5px;
padding-left: 0px;
}
.inline-list > li {
padding: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
cursor: pointer;
display: inline;
text-align: center;
text-decoration: none;
color: #606060;
display: inline-block;
}
.inline-list > li:focus-visible {
outline: 2px solid crimson;
}
.inline-list > li:hover {
color: crimson;
-moz-box-shadow:0 0 5px rgba(0,0,0,0.25);
-webkit-box-shadow:0 0 5px rgba(0,0,0,0.25);
box-shadow:0 0 5px rgba(0,0,0,0.25);
}
#spray-paint-control {
text-align: right;
}
#spray-paint-control .label {
min-width: 0px;
}
.inner-stroke {
stroke-width: 14;
stroke: white;
fill: none;
}
.stroke {
stroke-width: 18;
stroke: black;
fill: none;
stroke-linejoin: round;
stroke-linecap: round
}
#demo-status {
margin: 0.25em auto;
font-family: Tahoma, Verdana, system-ui, sans-serif;
font-size: 12px;
color: #8a1029;
}
/graffitis/graffiti-lib.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
/**
* @file
*
* This file contains a simple library to process the Graffiti Markup Language
* JSON data and compute commonly needed information from the strokes.
*/
YUI.add('graffiti-lib', function (Y) {
window.sw = window.sw || {};
sw.graffiti = sw.graffiti || {};
// Use an instance id to get a unique call back. See the request method.
var instanceId = 0;
var LOCAL_TAGS = {
'161': 'json/spiral.js',
'12526': 'json/wave.js'
};
/**
* Computes the speed on a stroke segment
*
* @param x starting point on the x axis
* @param y starting point on the y axis
* @param ex end point on the x axis
* @param ey end point on the y axis
* @param dt segment duration
*
* @return an object with the speed vector (sx, sy) and the speed value (s)
*/
function computeSpeed (x, y, ex, ey, dt) {
var dx = ex - x,
dy = ey - y,
speed;
if (dt > 0) {
speed = {
sx: dx / dt,
sy: dy / dt,
s: Math.sqrt(dx * dx + dy * dy) / dt
};
} else {
speed = {sx: 0, sy: 0, s: 0}
}
return speed;
}
/**
* Normalizes the gmlData: makes sure the stroke is an array and converts all
* the x/y/time coordinates to numbers.
*
* @param gmlData the original GML data JSON
* @return an array of strokePoints where string coordinates have been
* converted to numbers.
*/
function preprocessStrokePoints (gmlData) {
var strokes =
gmlData.gml.tag.drawing.stroke instanceof Array ?
gmlData.gml.tag.drawing.stroke :
[gmlData.gml.tag.drawing.stroke],
n = strokes.length,
strokePoints,
m;
for (var i = 0; i < n; i++) {
strokePoints = strokes[i].pt;
m = strokePoints.length;
for (var j = 0; j < m; j++) {
strokePoints[j].x = parseFloat(strokePoints[j].x);
strokePoints[j].y = parseFloat(strokePoints[j].y);
strokePoints[j].time = parseFloat(strokePoints[j].time);
}
}
return strokes;
}
/**
* Process the strokePoints to compute additional information.
*
* @param strokePoints the array of points to process.
* @param curDuration the duration of previoius strokes
* @param curLength the lenght of previous strokes
*/
function processStrokePoints (strokePoints, curDuration, curLength) {
var result = {
maxSpeed: 0, minSpeed: 0,
minX: 0, minY: 0, maxX: 0, maxY: 0
}, tagStartTimeOffset = curDuration;
if (strokePoints.length > 0) {
var curPoint = strokePoints[0],
nextPoint,
minX = curPoint.x, minY = curPoint.y,
maxX = curPoint.x, maxY = curPoint.y,
minSpeed, maxSpeed,
cx = curPoint.x, cy = curPoint.y,
pcx, pcy, ncx, ncy, dx, dy, d, ox, oy,
speedIn, speedOut,
ndt, // next segment's durations
processedPoints = [],
strokeDuration = 0, // total duration for the stroke
strokeLength = 0; // total length for the stroke
tagStartTimeOffset = strokePoints[0].time;
for (var i = 0; i < strokePoints.length; i++) {
curPoint = strokePoints[i];
if (i > 0) {
pcx = cx; pcy = cy;
cx = ncx; cy = ncy;
} else {
pcx = curPoint.x; pcy = curPoint.y;
cx = curPoint.x; cy = curPoint.y;
}
ndt = 0;
if (i < strokePoints.length - 1) {
nextPoint = strokePoints[i + 1];
ncx = nextPoint.x; ncy = nextPoint.y;
ndt = nextPoint.time - curPoint.time;
} else {
ncx = cx; ncy = cy; ndt = 0;
}
if (cx < minX) {minX = cx;}
if (cx > maxX) {maxX = cx;}
if (cy < minY) {minY = cy;}
if (cy > maxY) {maxY = cy;}
speedOut = computeSpeed(cx, cy, ncx, ncy, ndt);
if (i === 0) {
speedIn = {sx: 0, sy: 0, s: 0};
minSpeed = speedOut.s;
maxSpeed = speedOut.s;
} else {
speedIn = processedPoints[i - 1].speedOut;
if (minSpeed > speedIn.s) {minSpeed = speedIn.s;}
if (maxSpeed < speedIn.s) {maxSpeed = speedIn.s;}
}
dx = ncx - cx; dy = ncy - cy;
d = Math.sqrt(dx * dx + dy * dy);
ox = -dy;
oy = dx;
if (d > 0) { ox /= d; oy /= d; }
processedPoints.push({
// Point coordinates
x: cx, y: cy,
// Previous point coordinates
pcx: pcx, pcy: pcy,
// Next point coordinates
ncx: ncx, ncy: ncy,
// Segment vector and length
segment: {dx: dx, dy: dy, d: d},
// Orthogonal
orthogonal: {ox: ox, oy: oy},
// Speed in and out of the point. Each has sx, sy and s
// (intensity value)
speedIn: speedIn, speedOut: speedOut,
// Traversal time, on this stroke only
strokeTimeOffset: strokeDuration,
// Traversal time, accross strokes
// tagTimeOffset: curDuration + strokeDuration,
tagTimeOffset: curPoint.time,
// Length of the stroke up to this point, accross strokes
tagAdvance: curLength + strokeLength,
// Length of the stroke up to this point, on this stroke only
strokeAdvance: strokeLength
});
strokeDuration += ndt;
strokeLength += d;
}
result = {
points: processedPoints,
minSpeed: minSpeed,
maxSpeed: maxSpeed,
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY,
strokeDuration: strokeDuration,
strokeLength: strokeLength,
tagLength: curLength + strokeLength,
tagDuration: curDuration + strokeDuration, // Excludes pauses between strokes
tagStarTimeOffset: tagStartTimeOffset,
tagEndTimeOffset: tagStartTimeOffset + strokeDuration,
bounds: {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
}
};
}
return result;
}
/**
* Process the set of strokes.
*
* @param strokes the strokes to process.
*/
function processStrokes (strokes) {
var result = {
strokes: strokes,
strokesInfo: [],
points: [],
maxSpeed: 0, minSpeed: 0,
minX: 0, minY: 0, maxX: 0, maxY: 0,
tagDuration: 0,
tagLength: 0
},
n = strokes.length,
strokeInfo;
if (n > 0) {
strokeInfo =
processStrokePoints(strokes[0].pt, result.tagDuration, result.tagLength);
result.maxSpeed = strokeInfo.maxSpeed;
result.minSpeed = strokeInfo.minSpeed;
result.maxX = strokeInfo.maxX;
result.minX = strokeInfo.minX;
result.maxY = strokeInfo.maxY;
result.minY = strokeInfo.minY;
result.tagDuration = strokeInfo.strokeDuration;
result.tagLength = strokeInfo.strokeLength;
result.points.push.apply(result.points, strokeInfo.points);
result.strokesInfo.push(strokeInfo);
}
for (var i = 1; i < n; i++) {
strokeInfo =
processStrokePoints(strokes[i].pt, result.tagDuration, result.tagLength);
if (result.maxSpeed < strokeInfo.maxSpeed) {
result.maxSpeed = strokeInfo.maxSpeed;
}
if (result.minSpeed > strokeInfo.minSpeed) {
result.minSpeed = strokeInfo.minSpeed;
}
if (result.maxX < strokeInfo.maxX) {
result.maxX = strokeInfo.maxX;
}
if (result.minX > strokeInfo.minX) {
result.minX = strokeInfo.minX;
}
if (result.maxY < strokeInfo.maxY) {
result.maxY = strokeInfo.maxY;
}
if (result.minY > strokeInfo.minY) {
result.minY = strokeInfo.minY;
}
result.tagDuration += strokeInfo.strokeDuration;
result.tagLength += strokeInfo.strokeLength;
result.points.push.apply(result.points, strokeInfo.points);
result.strokesInfo.push(strokeInfo);
}
result.bounds = {
x: result.minX,
y: result.minY,
width: result.maxX - result.minX,
height: result.maxY - result.minY
};
return result;
}
/**
* @constructor computes the unique instance id
*/
var GraffitiLib = function () {
this.id = instanceId++;
// Events supported by this instance.
this.events = {
gmlLoaded: "sw:GraffitiLib:gmlLoaded"
};
}
GraffitiLib.prototype = {
/**
* Request new GML data
*
* @param gmlId the new GML id to retrive from blackbook
* @see http://jamiedubs.com/wikis/blackbook/#downloading-gml
*/
request: function (gmlId) {
// The remote tag repository is gone, so sample ids map to local files.
this.requestLocal(LOCAL_TAGS[gmlId] || 'json/svgwow.js');
},
/**
* Request new GML data from the local resources.
*
* @param relativeURL the new GML id to retrive
*/
requestLocal: function (relativeURL) {
// Same method as Flickr API: create a script element and add it to the
// SVG document. The callback will be called when the script is fully loaded
// var script = document.createElementNS(sw.svgNS, "script");
var script = document.createElement('script');
var callbackName = "onGraffitiLoad_local";
var url = relativeURL;
script.setAttribute("src", url);
var that = this;
GraffitiLib[callbackName] = function (gmlData) {
that.onGraffitiLoad(gmlData, 'local');
}
document.documentElement.appendChild(script);
},
/**
* General handler for receiving GML data
*
* @param gmlData the GML data retrieved from the network.
* @param gmlId the requested GML identifier
*/
onGraffitiLoad : function (gmlData, gmlId) {
// Preprocess the gmlData to extract the strokes and convert
// to numbers.
var strokes = preprocessStrokePoints(gmlData);
// Now, compute info such as speed and accesleration on each of the
// stroke points.
var graffitiMetrics = processStrokes(strokes);
this.fire({
type: "sw:GraffitiLib:gmlLoaded",
gmlData: gmlData,
gmlId: gmlId,
gmlMetrics: graffitiMetrics
});
}
};
Y.augment(GraffitiLib, Y.EventTarget);
sw.graffiti.GraffitiLib = GraffitiLib;
});/graffitis/graffitis-record.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
/**
* This module is used to capture drawing in a canvas and recod it as GML data.
*/
YUI.add("graffitis-record", function (Y) {
sw = sw || {};
/**
* Records a drawing happening on the given event target. The GraffitiRecorder
* generates events to notify listeners of updates in the graffiti. The
* <code>getStrokePath</code> and <code>getGML</code> can be called at any
* time to get the current status of the graffiti.
*
* @param eventTarget the DOM element where the different mouse events happen.
* A mousedown will start a new stroke and a mouseup will end the current
* stroke. A mouse move while the mouse is down will add a point to the
* current stroke.
*/
function GraffitiRecorder (eventTarget) {
var that = this;
// Pointer events cover both mouse and touch drawing.
var node = eventTarget._node;
this._listeners = {
pointerdown: function (evt) {
evt.preventDefault();
if (node.setPointerCapture) {
try { node.setPointerCapture(evt.pointerId); } catch (e) {}
}
that._onStartStroke(evt);
},
pointermove: function (evt) { that._onNewStrokePoint(evt); },
pointerup: function (evt) { that._onEndStroke(evt); },
pointercancel: function (evt) { that._onEndStroke(evt); }
};
Object.keys(this._listeners).forEach(function (type) {
node.addEventListener(type, that._listeners[type], false);
});
node.style.touchAction = 'none';
this._strokes = [];
this._curStroke = null;
this._recording = false;
this._startTime = 0;
this._started = false;
this._eventTarget = eventTarget;
}
GraffitiRecorder.events = {
newPoint: 'new-point',
newStroke: 'new-stroke',
strokeComplete: 'stroke-complete'
};
sw.GraffitiRecorder = GraffitiRecorder;
Y.mix(GraffitiRecorder.prototype, {
// =========================================================================
// Public methods
// =========================================================================
events: GraffitiRecorder.events,
/**
* Stops listening for input.
*/
stop : function () {
var node = this._eventTarget._node, listeners = this._listeners;
Object.keys(listeners).forEach(function (type) {
node.removeEventListener(type, listeners[type], false);
});
node.style.touchAction = '';
this._recording = false;
},
/**
* @return true when at least one stroke has two or more points.
*/
hasStrokes : function () {
return this._strokes.some(function (s) { return s.pt.length > 1; });
},
/**
* Computes the current state of the Graffiti as a GML data structure
*/
getGMLRecord : function () {
var bounds = this._eventTarget._node.getBoundingClientRect();
var gmlResult = {
"image_file_size": "unknown",
"updated-at": (new Date()).toString(),
"gml_application": "svg-wow",
"title": "SVG Wow recording",
"gml": {
"tag": {
"header": {
"client": {
name: "Graffiti Recorder 1.0, svg-wow.org",
username: "anonymous",
version: "1.0",
keywords: null
}
},
"environment": {
up: {
x: 0,
y: 1,
z: 0
}
},
"drawing": {
stroke: this._strokes.filter(function (s) {
return s.pt.length > 1;
})
}
}
}
};
return gmlResult;
},
// =========================================================================
// Implementation
// =========================================================================
_addPoint : function (x, y) {
var time = ((new Date()).getTime() - this._startTime) / 1000,
bounds = this._eventTarget._node.getBoundingClientRect();
// Convert to viewBox units, since the viewer may be scaled down.
x = (x - bounds.left) * 600 / bounds.width;
y = (y - bounds.top) * 400 / bounds.height;
this._curStroke.push({
x: x,
y: y,
z: 0,
time: time
});
this.fire({
type: this.events.newPoint,
x: x,
y: y,
time: time
});
},
_onStartStroke : function (evt) {
// Set the start time on the first stroke
if (this._started === false) {
this._startTime = (new Date()).getTime();
this._started = true;
}
// Record when we start a new stroke.
this._recording = true;
// Build the data structures to hold the new stroke points.
this._curStroke = [];
this._strokes.push({pt: this._curStroke});
// Add the initial stroke point.
this._addPoint(evt.clientX, evt.clientY);
},
_onEndStroke : function (evt) {
this._recording = false;
},
_onNewStrokePoint : function (evt) {
if (this._recording === true) {
this._addPoint(evt.clientX, evt.clientY);
}
}
});
Y.augment(GraffitiRecorder, Y.EventTarget);
});/graffitis/smooth.js
/** =======================================================================
* Vincent Hardy
* License terms: see svg-wow.org
* CC0 http://creativecommons.org/publicdomain/zero/1.0/
* ======================================================================= */
/**
* Utility method to convert an array of points (a polyline) into a set of
* cubic curve segments.
*
* If the input array has n points, the returned array has n-1 segments, each
* ending on points at index 1 to n-1 in the iput array.
*
* @param points the array of points defining a set of line segments
* @param s smoothness in the [0, 1] interval. 0 will keep straight segments and
* 1 is the smoothest.
* @return a set of cubic segments. An array containing 4 points where:
* - pt[0] is the start of the segment
* - pt[1] is the first control point
* - pt[2] is the second control point
* - pt[3] is the end of the cubic segment.
*/
function smooth (points, s) {
var n = points.length;
var segments = [];
var p_0, p_1, p_2, p_3;
var d, dx, dy;
var tx, ty;
var norm;
var w;
var tangents = [];
// No tangent on the first point
tangents.push({tx: 0, ty: 0});
// First, compute the tangent on each of the points
for (var i = 1; i < n - 1; i++) {
tx = points[i + 1].x - points[i - 1].x;
ty = points[i + 1].y - points[i - 1].y;
norm = Math.sqrt(tx * tx + ty * ty);
if (norm > 0) {
tangents.push({tx: tx / norm, ty: ty / norm});
} else {
tangents.push({tx: 0, ty: 0});
}
}
// No tangent on the last point
tangents.push({tx: 0, ty: 0});
// Now, compute the segments.
for (i = 1; i < n; i++) {
p_0 = points[i - 1];
p_3 = points[i];
dx = p_3.x - p_0.x;
dy = p_3.y - p_0.y;
d = Math.sqrt(dx * dx + dy * dy);
w = s * d / 2;
p_1 = {
x: p_0.x + w * tangents[i - 1].tx,
y: p_0.y + w * tangents[i - 1].ty
};
p_2 = {
x: p_3.x - w * tangents[i].tx,
y: p_3.y - w * tangents[i].ty
};
segments.push([p_0, p_1, p_2, p_3]);
}
return segments;
}/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);
}
};
})();