this example uses d3 to manipulate paths inside of an svg loaded from an external file.
the D3 logo svg is from the eponymous D3 Logo bl.ock
this example is based on earlier research for the bl.ock Sporthorse Foal Registrations II. I’ve found this technique useful again recently, and thought it deserved a few examples of its own.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>External SVG + D3</title>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
/* Make the chart container fill the page using CSS. */
#chart {
position: fixed;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
</style>
</head>
<body>
<div id="vis"></div>
<script>
// Extract the width and height that was computed by CSS.
var chartDiv = document.getElementById("vis");
var width = chartDiv.clientWidth;
var height = chartDiv.clientHeight;
// load the external svg from a file
d3.xml("d3.svg", "image/svg+xml", function(xml) {
var importedNode = document.importNode(xml.documentElement, true);
d3.select("div#vis")
.each(function() {
this.appendChild(importedNode);
})
// inside of our d3.xml callback, call another function
// that styles individual paths inside of our imported svg
styleImportedSVG()
});
function styleImportedSVG () {
d3.select('svg')
.on('mouseover', function() {
console.log('mouseover');
console.log('this', this);
d3.selectAll('path')
.style({
'fill-opacity': 0.1,
'stroke-opacity': 0.3
})
})
.on('mouseout', function() {
console.log('mouseout');
d3.selectAll('path')
.style({
'fill-opacity': 1,
'stroke-opacity': 1
})
})
}
</script>
</body>
</html>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="-10 -10 116 111">
<clipPath id="clip">
<path d="M0,0h7.75a45.5,45.5 0 1 1 0,91h-7.75v-20h7.75a25.5,25.5 0 1 0 0,-51h-7.75zm36.2510,0h32a27.75,27.75 0 0 1 21.331,45.5a27.75,27.75 0 0 1 -21.331,45.5h-32a53.6895,53.6895 0 0 0 18.7464,-20h13.2526a7.75,7.75 0 1 0 0,-15.5h-7.75a53.6895,53.6895 0 0 0 0,-20h7.75a7.75,7.75 0 1 0 0,-15.5h-13.2526a53.6895,53.6895 0 0 0 -18.7464,-20z"/>
</clipPath>
<linearGradient id="gradient-1" gradientUnits="userSpaceOnUse" x1="7" y1="64" x2="50" y2="107">
<stop offset="0" stop-color="#f9a03c"/>
<stop offset="1" stop-color="#f7974e"/>
</linearGradient>
<linearGradient id="gradient-2" gradientUnits="userSpaceOnUse" x1="2" y1="-2" x2="87" y2="84">
<stop offset="0" stop-color="#f26d58"/>
<stop offset="1" stop-color="#f9a03c"/>
</linearGradient>
<linearGradient id="gradient-3" gradientUnits="userSpaceOnUse" x1="45" y1="-10" x2="108" y2="53">
<stop offset="0" stop-color="#b84e51"/>
<stop offset="1" stop-color="#f68e48"/>
</linearGradient>
<g clip-path="url(#clip)">
<path d="M-100,-102m-28,0v300h300z" fill="url(#gradient-1)"/>
<path d="M-100,-102m28,0h300v300z" fill="url(#gradient-3)"/>
<path d="M-100,-102l300,300" fill="none" stroke="url(#gradient-2)" stroke-width="40"/>
</g>
</svg>