【问题标题】:D3 fill pie chart segment on mouseover鼠标悬停时 D3 填充饼图段
【发布时间】:2018-10-15 20:41:30
【问题描述】:

我有一个这样定义的饼图:

var pie = d3.pie()
    .sort(null)
    .value(function(d) { return +d.value; });

var path = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0.65*radius);

var arc = g.selectAll(".arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")

arc.append("path")
    .attr("d", path)
    .attr("fill", function(d, i) { return colours[i]; }) //Everything up to here works
    .on('mouseover', function() {console.log('over'); arc.style("fill","red");});

最后一行只工作了一半——控制台确实打印了“over”,但该段不会改变颜色。这是错误的方法吗?

【问题讨论】:

    标签: html css d3.js tooltip mouseover


    【解决方案1】:

    您应该使用d3.select(this) 而不是arc 选择当前悬停的元素:

    // .on('mouseover', function() { arc.style("fill","red"); });
    .on('mouseover', function() { d3.select(this).style("fill","red"); });
    

    这是一个演示:

    var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height");
    
    var g = svg.append("g").attr("transform", "translate(100,100)")
    
    var data = [
      { value: 4 }, { value: 12 }
    ];
    var colours = ["green", "blue"];
    var radius = 25;
    
    var pie = d3.pie()
        .sort(null)
        .value(function(d) { return +d.value; });
    
    var path = d3.arc()
        .outerRadius(radius - 10)
        .innerRadius(0.65*radius);
    
    var arc = g.selectAll(".arc")
        .data(pie(data))
        .enter()
        .append("g")
        .attr("class", "arc")
    
    arc.append("path")
        .attr("d", path)
        .attr("fill", function(d, i) { return colours[i]; }) //Everything up to here works
        // .on('mouseover', function() { console.log('over'); arc.style("fill","red"); });
        .on('mouseover', function() { console.log('over'); d3.select(this).style("fill","red"); });
    <svg width="960" height="600"></svg>
    <script src="https://d3js.org/d3.v4.min.js"></script>

    【讨论】:

    • 完美,谢谢。如何让它在鼠标关闭时恢复到原来的颜色? .on('mouseoff', function() { d3.select(this).style("fill","ORIGINAL"); });
    • 你可以使用:.on('mouseout', function(d, i) { d3.select(this).style("fill", colours[i]); });,其中i代表data中弧的索引。
    猜你喜欢
    • 2015-04-22
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多