D3 js - 添加标签或文字以拖放圆圈

时间:2017-03-10 20:35:08

标签: javascript html d3.js

我使用这个tutorial来创建一组圆圈,通过读入属性将它们排成一行,对它们进行颜色编码,并使它们可移动(拖放)。我知道我需要创建一个节点'并附加' circle'和'文字'到每个节点,但我无法全部合作。

<!DOCTYPE html>
<html>
<head>
    <title>Set Lineups</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="d3.js"></script>
    <style>
        body {padding: 15px}
        .active {
            stroke: #000;
            stroke-width: 2px;
        }
        text {
            font: 10px sans-serif;
            pointer-events: none;
            text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
        }
    </style>
</head>

<body>
<!--begin svg block-->
    <svg width="960" height="500"></svg>
    <script>
    //now in js

    //define variables
    var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height"),
        radius = 32;

    // setup x
    var xValue = function(d) {
        if (d.Side == "Starboard") {return x=Math.round(2*radius)}
            else if (d.Side == "BiStar") {return x=Math.round(2*radius)}
            else if (d.Side == "Port") {return x=Math.round(5*radius)}
            else if (d.Side == "BiPort") {return x=Math.round(5*radius)}
            else if (d.Side == "Cox") {return x=Math.round(8*radius)}
    }

    // setup y
    var yPort = 0
    var yStar = 0
    var yCox = 0
    var yValue = function(d) {
        if (d.Side == "Starboard") {
            y = Math.round(2*radius) + yStar;
            yStar = y;
            return y}
            else if (d.Side == "BiStar") {
                y = Math.round(2*radius) + yStar;
                yStar = y;
                return y}
            else if (d.Side == "Port") {
                y = Math.round(2*radius) + yPort;
                yPort = y;
                return y}
            else if (d.Side == "BiPort") {
                y = Math.round(2*radius) + yPort;
                yPort = y;
                return y}
            else if (d.Side == "Cox") {
                y = Math.round(2*radius) + yCox;
                yCox = y;
                return y}
    }

    //read in the data
    d3.csv("Roster.csv", function(data) {
        data.forEach(function(d) {
            name : d["Full Name"];
            side : d["Side"];
            injured : d["Injured"];
            absent : d["Absent"];
            console.log(d);
        });

        var node = svg.selectAll(".node")
            .data(data)
          .enter().append("g")
            .attr("class", "node")
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended));

        node.append("circle")
            .style("fill", function(dg, i) { 
                if (dg.Side == "Port") {color = "red"}
                    else if (dg.Side == "Starboard") {color = "green"}
                    else if (dg.Side == "BiPort") {color = "orange"}
                    else if (dg.Side == "BiStar") {color = "blue"}
                    else if (dg.Side == "Cox") {color = "grey"}
                if (dg.Injured == "Yes") {color = "yellow"}
                if (dg.Absent == "Yes") {color = "yellow"}
                return color;
            })
            .attr("cx", function(dg) { return xValue(dg); })
            .attr("cy", function(dg) { return yValue(dg); })

        node.append("text")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .attr("cx", function(dg) { return xValue(dg); })
            .attr("cy", function(dg) { return yValue(dg); })
            .text(function(dg) {return dg['Full Name']});


        function dragstarted(dg) {
          d3.select(this).raise().classed("active", true);
        }

        function dragged(dg) {
          d3.select(this).attr("cx", dg.x = d3.event.x).attr("cy", dg.y = d3.event.y);
        }

        function dragended(dg) {
          d3.select(this).classed("active", false);
        }

    })
</script>
</body>

以下是数据的快照:

全名侧伤缺席

Name0 Port No No

名称1右舷否否

Name2右舷否是

名称2 BiPort否否

Name3 BiStar否否

Name4 Starboard是否

姓名5考克斯否否

1 个答案:

答案 0 :(得分:0)

您有正确的方法,但如果您将变换分配给节点(或g元素),以便默认情况下文本和圆圈对齐,我会采用这种方法回答(虽然您可以重新计算节点的移动并单独重新计算文本和圆坐标)

您可能遇到困难的中心,您会看到在拖动功能中设置属性cxcy

d3.select(this).attr("cx", dg.x = d3.event.x).attr("cy", dg.y = d3.event.y);

但是拖动的g / node元素没有这些属性 - 这些是该行引用的this。这是因为您最初将拖动功能移动到最初附加到圆圈的节点上。

相反,将上面的行替换为可以重新计算拖动的g /节点的变换的行。这将在拖动的g /节点(以及任何其他子节点)内更新文本和圆圈。

当然,如果对每个g /节点使用转换,则根本不需要使用圈子的cxcy属性。

它们看起来像这样:

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height"),
    radius = 32;

var circles = d3.range(20).map(function() {
  return {
    x: Math.round(Math.random() * (width - radius * 2) + radius),
    y: Math.round(Math.random() * (height - radius * 2) + radius)
  };
});

var color = d3.scaleOrdinal()
    .range(d3.schemeCategory20);
    
var circleGroup = svg.selectAll('g')
  .data(circles)
  .enter().append('g')
  .attr('transform',function(d) { return 'translate('+d.x+','+d.y+')'; })
    .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

circleGroup.append("circle")
    .attr("r", radius)
    .style("fill", function(d, i) { return color(i); })

circleGroup.append("text")
   .text(function(d,i) { return i; })
   .style('text-anchor','middle')
   .attr('y',4);


function dragstarted(d) {
  d3.select(this).raise().classed("active", true);
}

function dragged(d) {
  d3.select(this).attr("transform","translate("+(d.x = d3.event.x)+','+(d.y = d3.event.y)+')' );
}

function dragended(d) {
  d3.select(this).classed("active", false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>
<svg width="500" height="300"></svg>