svg=d3.select"body".append"svg"rect=svg.append"rect"rect.attr"width",100.attr"height",200.style"fill","#eef"text=svg.append"text"text.attr"x",2.attr"y",2.style"dominant-baseline","text-before-edge".text"some long text so I can try out laying elements vertically that require word wrapping".wordwrap96# wrap to 96 px
wordwrap=(width) ->this.each() ->text=d3.selectthiswords=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, 10tspan=text.textnull.append"tspan"whilewords.length>0word=words.pop()line.pushwordtspan.textline.join" "iftspan.node().getComputedTextLength()>=widthline.pop()tspan.textline.join" "line=[word]tspan=text.append"tspan".attr"dy",line_height+"px".attr"dx",-tspan.node().getComputedTextLength()+"px".textwordd3.selection.prototype.wordwrap=wordwrap
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.