Skip to content

Instantly share code, notes, and snippets.

@micahstubbs
Created April 3, 2016 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micahstubbs/fdb0bd65bbfcc57b60bd9d80debb4233 to your computer and use it in GitHub Desktop.
Save micahstubbs/fdb0bd65bbfcc57b60bd9d80debb4233 to your computer and use it in GitHub Desktop.
External SVG + D3 II
license: CC0-1.0
height: 960
border: no

this example uses d3 to manipulate paths inside of an svg loaded from an external file.

the image is the famous Ghostscript Tiger.svg

hat tip to @ocampesato for introducing me to the SVG Tiger

this exmaple 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.

Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!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("Ghostscript_Tiger.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.selectAll('path')
.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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment