首页 文章

无法创建SVG组

提问于
浏览
1

使用d3.js,我正在尝试创建一系列SVG组(即 <g> 元素),并为数据数组中的每个数字添加 <g> 元素 . 每个 <g> 元素本身应包含 <rect><text> . 以下代码在我看来应该这样做,但是当我检查 <svg> 元素(在Chrome和Firefox中)时,它直接在 <svg> 元素内包含 <rect> 元素和 <text> 元素,看不到 <g> 元素 .

HTML页面最初只包含一个空的 <svg> 元素 . dataset 只是一个简单的数字数组 .

var svg = d3.select("svg");

svg.selectAll("g")
    .data(dataset)
    .enter()
    .call( function(g) {
        g.append("rect")
            .attr("x", (d, i) => xScale(i))
            .attr("y", d => h - yScale(d))
            .attr("width", xScale.rangeBand())
            .attr("height", d => yScale(d))
            .attr("fill", d => "rgb(0,0," + (d*10) + ")")
            .on('click', d => console.log(d))
            .on('mouseover', function() {
                d3.select(this)
                    .attr('fill', 'orange');
                })
            .on('mouseout', function(d) {
                d3.select(this)
                    .transition()
                    .duration(250)
                    .attr("fill", d => "rgb(0,0," + (d*10) + ")")
                });
        })
    .call( function(g) {
        g.append('text')
            .text(d => d)
            .attr('class','label')
            .attr("x", (d, i) => xScale(i) + xScale.rangeBand() / 2)
            .attr("y", d =>  h - yScale(d) + 14);
        });

1 回答

  • 1

    我发现了我的问题 . 我认为 selectAll('g').data(dataset).enter() 会导致 <g> 元素与 dataset 中为我创建的数据不匹配 . 但是在调用 .enter() 之后添加 .append('g') 以实际创建缺失的 <g> 元素是必要的 . 之后, .call(...) 调用的函数将传递给新的 <g> 元素 .

相关问题