This sample draw sentence line by line. the position variable currently always increase, how to reset it to 10 when new sentence start!
console.clear()
var data = `Hello word,d3.js.
Drawing with d3 is funny!
I like to play with it.`
var root = []
var sentences = data.split('\n')
sentences.forEach(d => {
root.push(d.split(' '))
})
var svg = d3.select('body').append('svg')
.attr('width',300)
.attr('hegith',300)
.style('border','5px solid red')
var pos = 10
var gbox = d3.local()
var lines = svg.selectAll('lines')
.data(root).enter()
.append('g')
.attr('transform',(d,i) => {
return `translate(0,${i*20})`
})
var words = lines.selectAll('text')
.data(d => d).enter()
.append('text')
.text(d => d)
.attr('fill','black')
.each((d,i,n) => {
var bbox = d3.select(n[i]).node().getBBox()
gbox.set(n[i],bbox)
})
.attr('x',(d,i,n) => {
var bbox = gbox.get(n[i])
var curr = pos
pos += bbox.width + 2
return curr
})
.attr('y',20)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>