Snippets

Adam Labadorf Flexible wordwrap with D3 and coffeescript

You are viewing an old version of this snippet. View the current version.
Revised by Adam Labadorf 6102802
wordwrap = (width) ->
  this.each () ->
    text = d3.select this
    words = text.text().split(/\s+/).reverse()
    line = []
    line_height = text.node().getBBox().height
    # can get the actual font height, but on chrome it seems like getBBox().height
    # is more accurate
    #line_height = parseInt window.getComputedStyle(this).fontSize, 10
    tspan = text.text null
      .append "tspan"

    while words.length > 0 
      word = words.pop()
      line.push word
      tspan.text line.join " " 
      if tspan.node().getComputedTextLength() >= width
        line.pop()
        tspan.text line.join " " 
        line = [word]
        tspan = text.append "tspan"
          .attr "dy", line_height + "px"
          .attr "dx", -tspan.node().getComputedTextLength() + "px"
          .text word
d3.selection.prototype.wordwrap = wordwrap
HTTPS SSH

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