Forked from alykat/gist:5fabb42475a6111ccc38591bac09550a
Created
April 4, 2016 17:16
-
-
Save joshuarrrr/8d1be97a16cbb2e865b3b0a0d70ac55a to your computer and use it in GitHub Desktop.
D3: Wrap label text and make SVG taller
This file contains hidden or 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
/* | |
* Wrap a block of text to a given width | |
* via http://bl.ocks.org/mbostock/7555321 | |
*/ | |
var wrapText = function(texts, width, lineHeight) { | |
texts.each(function() { | |
var text = d3.select(this); | |
var words = text.text().split(/\s+/).reverse(); | |
var word = null; | |
var line = []; | |
var lineNumber = 0; | |
var x = text.attr('x'); | |
var y = text.attr('y'); | |
var dx = parseFloat(text.attr('dx')); | |
var dy = parseFloat(text.attr('dy')); | |
var tspan = text.text(null) | |
.append('tspan') | |
.attr('x', x) | |
.attr('y', y) | |
.attr('dx', dx + 'px') | |
.attr('dy', dy + 'px'); | |
while (word = words.pop()) { | |
line.push(word); | |
tspan.text(line.join(' ')); | |
if (tspan.node().getComputedTextLength() > width) { | |
line.pop(); | |
tspan.text(line.join(' ')); | |
line = [word]; | |
lineNumber += 1; | |
tspan = text.append('tspan') | |
.attr('x', x) | |
.attr('y', y) | |
.attr('dx', dx + 'px') | |
.attr('dy', lineNumber * lineHeight) | |
.attr('text-anchor', 'begin') | |
.text(word); | |
} | |
} | |
var bbox = text.node().getBBox(); | |
if ((bbox.y + bbox.height) > (chartHeight + margins['bottom'])) { | |
chartHeight = (bbox.y + bbox.height) - margins['bottom']; | |
d3.select('svg') | |
.attr('height', chartHeight + margins['top'] + margins['bottom']); | |
} | |
}); | |
} | |
/* | |
* Render values to chart. | |
*/ | |
var values = d3.select('svg').append('g') | |
.attr('class', 'value'); | |
values.append('text') | |
.html(chartData['label']) | |
.classed('label', true) | |
.attr('x', xScale(chartData['label'])) | |
.attr('y', 25) | |
.attr('dx', 0) | |
.attr('dy', 0) | |
.call(wrapText, 80, 13); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment