阅读 spec 后和 this question我明白,渲染顺序实际上是一个时序顺序。
<svg>
的子元素根据渲染时间在 z 轴上排序,这意味着首先渲染的元素位于底部,最后渲染的元素位于同一区域中所有其他元素的顶部。
对于组元素 ( <g>
),这是否有所不同?
如果你看this code (a JsFiddle)结果,辅助线(<line>
元素)位于图形线(<path>
元素)之上。辅助线分组在轴组内,每条图形线将绘制在单独的组中。
但是轴首先渲染,至少是函数addYAxis
在 handleLine
之前调用运行。我在这里缺少什么?
注意:在 this answer 中,处理图表中红色圆圈和蓝色方 block 的渲染,指出
In this case the red circle will be visible above the blue square even though the blue square was created last. This is because the circle and the square are children of different group elements, which are in a pre-defined order.
但我不明白为什么这是可能的以及如何设置这个预定义顺序。
最佳答案
如果您希望轴线位于折线图后面,则可以。
首先创建x轴组和y轴组,然后创建直线组。 这可确保保留顺序。
在 setSVG 函数中执行以下操作:
parts.svg.append('defs').append('clipPath') //add a clip
.attr('id', lineWrapperId)
.append('rect')
.attr({
width: basics.width + 'px',
height: basics.height + 'px'
});
parts.svg.append('g') // add x axis g
.attr('class', 'x-axis');
parts.svg.append('g') // add y axis g
.attr('class', 'y-axis');
//finally add line group
parts.pathFrame = parts.svg.append('g') // add lines group
.attr('clip-path', 'url(#' + lineWrapperId + ')')
.attr('class', 'line-wrapper');
现在,当您使 x 轴选择其组并在函数 addXAxis 和 addYAxis
中使轴如下所示:
if (!parts.axisX) {
parts.axisX = d3.select(".x-axis") //selectin the x axis group
.attr({
'class': 'x-axis',
transform: 'translate(0,' + (basics.height - basics.margin) + ')'
})
.call(xAxis); // leave out tick sizes for now
} else {
parts.axisX = d3.select('g.x-axis')
.call(xAxis);
}
工作示例 here
关于javascript - 使用 d3.js 的组元素 (<g>) 的渲染顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34391972/