<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.8/chance.min.js"></script>
</head>
<body>
<script>
var w = 300,
h = 300;
var data = [
{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
}
]
var svg = d3.select('body')
.append('svg')
.attr('width', w)
.attr('height', h);
const labels = svg.selectAll('text').data(data);
labels.enter()
.append('text')
.attr('class', (d) => `label-${d.t}`)
.attr('x', (d) => d.x)
.attr('y', (d) =>d.y)
.text((d) => d.t)
.each(function(d){
var bbox = this.getBBox();
svg.append('rect')
.attr('x', bbox.x)
.attr('y', bbox.y)
.attr('width', bbox.width)
.attr('height', bbox.height)
.style('fill', 'none')
.style('stroke', 'steelblue');
});
</script>
</body>
</html>
,我不得不去'。每次((d,I,J)= > {const bbox = j [i] .getBBox(); ...}'來完成這個工作,但是你的代碼工作。謝謝 – Benjamin
@Benjamin,這是因爲你正在使用胖箭頭符號而不是常規函數''='' ,通過設計,壓制通過將'this'放入函數中。 – Mark