Snippets

Adam Labadorf Stacking selections in D3 with coffeescript

Created by Adam Labadorf last modified Adam Labadorf
svg = d3.select "body"
      .append "svg"
svg.attr "width", 300
   .attr "height", 300
bg = svg.append "rect"
bg.attr "width", 300
  .attr "height", 300
  .style "fill", "#eef"
g = svg.append "g"
g.attr "id", "parent"
 .attr "transform", "translate(30,30)"

t1 = g.append "text"
t1.style "dominant-baseline", "text-before-edge"
  .text "some text"

r1 = g.append "rect"
r1.attr "height", 32
  .attr "width", 200
  .style "fill", "red"
  .style "opacity", 0.75
            
t2 = g.append "text"
t2.attr "x", 0 
  .attr "y", 0
  .style "dominant-baseline", "text-before-edge"
  .text "some other text"

g.selectAll("*")
 .layout("vertical")
d3.selection::layout = (direction,hpad=0,vpad=0) ->
    dx = 0
    dy = 0
    this.each ->
        el = d3.select this
        transf = d3.transform(el.attr "transform")
        x = transf.translate.x ? 0
        y = transf.translate.y ? 0
        if direction in ["vertical","both"]
            y = dy
            el_height = d3.select(this).node().getBBox().height
            dy += el_height+vpad
        if direction in ["horizontal","both"]
            x = dx
            el_width = d3.select(this).node().getBBox().width
            dx += el_width+hpad
        el.attr "transform", "translate(#{x},#{y})"

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.