Built with blockbuilder.org
Last active
April 30, 2020 23:51
-
-
Save tomshanley/c041c5041f07a8a11529743cee58ae6a to your computer and use it in GitHub Desktop.
bbox example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
</style> | |
</head> | |
<body> | |
<script> | |
console.clear() | |
let data = [ | |
{"id": 1, "heading": "Node 1", "description": "longer description for the node"}, | |
{"id": 12, "heading": "Node 2", "description": "longer longer longer description for the node"} | |
] | |
let width = 500 | |
let height = 200 | |
let svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
let nodes = svg.selectAll(".node") | |
.data(data) | |
.enter() | |
.append("g") | |
.attr("transform", (d,i) => "translate(250," + (i * 60 + 50) +")") | |
let rects = nodes.append("rect") | |
.attr("id", d => "rect-" + d.id) | |
let headings = nodes.append("text") | |
.text(d => d.heading) | |
.attr("id", d => "heading-" + d.id) | |
.attr("y", 12) | |
.style("font-size", 24) | |
.style("text-anchor", "middle") | |
let descriptions = nodes.append("text") | |
.text(d => d.description) | |
.attr("id", d => "description-" + d.id) | |
.attr("y", 32) | |
.style("text-anchor", "middle") | |
let rectPadding = 2 | |
rects.attr("width", function(d){ | |
let headingid = "#heading-" + d.id | |
let descriptionid = "#description-" + d.id | |
let headingbbox = d3.select(headingid).node().getBBox(); | |
let descriptionbbox = d3.select(descriptionid).node().getBBox(); | |
//console.log(headingbbox) | |
//console.log(descriptionbbox) | |
d.x = d3.min([headingbbox.x, descriptionbbox.x]) - rectPadding | |
d.y = d3.min([headingbbox.y, descriptionbbox.y]) - rectPadding | |
d.width = d3.max([headingbbox.width, descriptionbbox.width]) + (rectPadding * 2) | |
d.height = d3.max([(headingbbox.height - headingbbox.y), (descriptionbbox.height - descriptionbbox.y)]) - d.y + (rectPadding * 2) | |
return d.width | |
}) | |
.attr("x", d => d.x) | |
.attr("y", d => d.y) | |
.attr("height", d => d.height) | |
.style("stroke", "black") | |
.style("fill", "lightgrey") | |
d3.selectAll("text") | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment