D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tomshanley
Full window
Github gist
bbox example
Built with
blockbuilder.org
<!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>
https://d3js.org/d3.v4.min.js