作为
d3.treemap()
svg
元素有嵌套
groups
rect
和
text
tspan
这样地:
<g><rect></rect><text><tspan>Text here</tspan></text></g>
treemap
const calculateCenterOfTextInRectangle = (tspanNode) => {
const rectangleNode = tspanNode.parentElement.previousSibling.previousSibling; // tspan is in text element and 2 nodes above is the rectangle
const centerX = (rectangleNode.getAttribute('width') / 2) - (tspanNode.getComputedTextLength() / 2);
const centerY = (rectangleNode.getAttribute('height') / 2) + (19 / 2); // 19 is the font-size in pixel
return {centerX: centerX,
centerY: centerY}; };
如果
height
width
矩形的大小不变。但是用户可以选择不同的选项来更改矩形的大小并触发此操作
d3.transition()
treemap(root.sum(sum)); // new values
cell.transition()
.duration(750)
.attr('transform', (d) => 'translate(' + d.x0 + ',' + d.y0 + ')')
.selectAll('rect')
.attr('width', (d) => d.x1 - d.x0)
.attr('height', (d) => d.y1 - d.y0);
setInterval(
() => {
cell.selectAll('tspan')
.attr('x', function() { return calculateCenterOfTextInRectangle(this).centerX; }) // center x and y. Not using Es6 function because of this context which is the tspan element.
.attr('y', function() { return calculateCenterOfTextInRectangle(this).centerY; });
},
0.1
);
问题是,当使用
setInterval
transition