Skip to content

Instantly share code, notes, and snippets.

@jocafa
Last active August 29, 2015 14:04
Show Gist options
  • Save jocafa/dc2bc54314079f71045b to your computer and use it in GitHub Desktop.
Save jocafa/dc2bc54314079f71045b to your computer and use it in GitHub Desktop.
SVG Reuse Across Embedded Documents With Filters

SVG Reuse Across Embedded Documents With Filters

<!DOCTYPE html>
<html>
<head>
<title>SVG Reuse Across Embedded Documents With Filters</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var
values = [
{name: "foo", value: 1},
{name: "bar", value: 2},
{name: "baz", value: 3},
{name: "qux", value: 4}
],
arcGen = d3.svg.arc()
.innerRadius(0)
.outerRadius(50),
pieLayout = d3.layout.pie()
.value(function (d) {
return d.value;
}),
colorScale = d3.scale.category10();
function randomizeValues() {
var i, l;
for (i = 0, l = values.length; i < l; i++) {
values[i].value = Math.random() * 10;
}
}
function renderMaster() {
var
data = pieLayout(values),
sliceSelection =
d3.select('#slices')
.selectAll('path')
.data(data, function (d, i) {
return d.data.name;
});
sliceSelection.enter()
.append('path')
.each(function (d, i) {
this._current = d;
})
.attr('id', function (d, i) {
return 'slice-' + d.data.name;
})
.attr('d', function (d, i) {
return arcGen({
startAngle: 0,
endAngle: 0
});
})
.attr('fill', function (d, i) {
return colorScale(d.data.name);
});
sliceSelection.transition().duration(1000)
.attrTween('d', function (d) {
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function (t) {
return arcGen(interpolate(t));
};
});
}
function createSlaves() {
var
i, j, l,
slaveSvg = d3.select('#pieSlave'),
slave,
slaveSlice;
for (i = 0, l = values.length; i < l; i++) {
slave = slaveSvg.append('g')
.attr('class', 'slave-' + values[i].name)
.attr('transform', 'translate(' + (200+120*i) + ', 50)');
for (j = 0; j < l; j++) {
slave.append('g')
.attr('filter', (i != j) ? 'url(#bland)' : null)
.append('use')
.attr('xlink:href', '#slice-' + values[j].name);
}
}
}
function randomize() {
randomizeValues();
renderMaster();
}
renderMaster();
createSlaves();
window.setInterval(randomize, 5000);
});
</script>
</head>
<body>
<h1>Master</h1>
<svg id="pieMaster" width="100" height="100">
<defs>
<filter id="bland">
<feComponentTransfer>
<feFuncR type="discrete" tableValues="0.5" />
<feFuncG type="discrete" tableValues="0.5" />
<feFuncB type="discrete" tableValues="0.5" />
</feComponentTransfer>
</filter>
<g id="slices">
</g>
</defs>
<use x="50" y="50" xlink:href="#slices" />
</svg>
<h1>Slave</h1>
<svg id="pieSlave" width="620" height="100">
<use x="50" y="50" xlink:href="#slices" />
</svg>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment