Skip to content

Instantly share code, notes, and snippets.

@Fil
Last active April 26, 2019 16:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fil/e63ed26c49e6e236553965f605d25f2f to your computer and use it in GitHub Desktop.
Save Fil/e63ed26c49e6e236553965f605d25f2f to your computer and use it in GitHub Desktop.
Fitted Symbols (d3v4)
license: gpl-3.0

This example demonstrates how to scale a D3 symbol to fit inside a specified rectangular bounding box using getBBox.

forked from mbostock's block: Fitted Symbols (d3v3)

<!DOCTYPE html>
<meta charset="utf-8">
<style>
rect {
fill: none;
stroke: #aaa;
stroke-width: 2px;
shape-rendering: crispEdges;
}
</style>
<svg width="960" height="500">
<rect width="400" height="400" x="280" y="50"/>
<g transform="translate(480,250)">
<path id="symbol"/>
</g>
</svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var path = d3.select("path"),
rect = d3.select("rect"),
width = +rect.attr("width"),
height = +rect.attr("height");
var symbol = d3.symbol(),
symbolIndex = -1,
symbolTypes = d3.symbols;
setInterval(function() {
symbolIndex = (symbolIndex + 1) % symbolTypes.length;
symbol.type(symbolTypes[symbolIndex]);
path.attr("d", symbol.size(64));
var box = path.node().getBBox(),
error = Math.min(width / box.width, height / box.height);
path.transition().duration(1500).attr("d", symbol.size(error * error * 64));
}, 2000);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment