2017-06-18 59 views
0

我對d3js v3很新穎,我正在嘗試一個新的程序,其中有行和根據數據,圓圈嵌入到它們中。D3js通過拖放動態地將圓圈連成一條線

這是我到目前爲止。

var width = 500, 
 
    height = 500; 
 

 
var animals = ['dog', 'cat', 'bat']; 
 
var fruits = ['apple', 'banana']; 
 

 

 
var svg = d3.select("body") 
 
    .append("svg") 
 
    .attr("width", width) 
 
    .attr("height", height); 
 

 
var line1 = svg.append("line") 
 
    .attr("x1", 350) 
 
    .attr("y1", 5) 
 
    .attr("x2", 350) 
 
    .attr("y2", 350) 
 
    .attr("stroke-width", 2) 
 
    .attr("stroke", "black"); 
 

 
var line2 = svg.append("line") 
 
    .attr("x1", 80) 
 
    .attr("y1", 5) 
 
    .attr("x2", 100) 
 
    .attr("y2", 350) 
 
    .attr("stroke-width", 2) 
 
    .attr("stroke", "black"); 
 

 
var animal_scale = d3.scale.ordinal() 
 
    .domain(animals) 
 
    .rangePoints([5, 350],.2); 
 

 
var fruit_scale = d3.scale.ordinal() 
 
    .domain(fruits) 
 
    .rangePoints([5, 350],.2); 
 

 

 
var animal_circles = svg.selectAll('circle') 
 
    .data(animals) 
 
    .enter() 
 
    .append('circle') 
 
    .attr('cx', function(d) { 
 
    // is there a way to calc it automatically according to line 1 
 
    }) 
 
    .attr('cy', function(d) { 
 
    return animal_scale(d); 
 
    }) 
 
    .attr('id', function(d) { 
 
    return d; 
 
    }) 
 
    .attr('r', 20); 
 

 
var fruits_circles = svg.selectAll('circle') 
 
    .data(fruits) 
 
    .enter() 
 
    .append('circle') 
 
    .attr('cx', function(d) { 
 
    // is there a way to calc it automatically according to line 2 
 
    }) 
 
    .attr('cy', function(d) { 
 
    return fruit_scale(d); 
 
    }) 
 
    .attr('id', function(d) { 
 
    return d; 
 
    }) 
 
    .attr('r', 20);
<!DOCTYPE html> 
 
<html> 
 
<meta charset=utf-8> 
 

 
<head> 
 
    <title></title> 
 
</head> 
 

 
<body> 
 

 
    <script src="https://d3js.org/d3.v3.min.js"></script> 
 

 
</body> 
 

 
</html>

我看了一些資料,併爲新的,它有點難以理解大部分。我最終希望能夠在項目結束時在行之間移動和拖動圓圈。當前代碼存在一些問題,因爲它不會顯示第二組圓。

有人可以幫助我進一步瞭解如何做到這一點。這對我來說是一個很好的學習方式。

回答

0

您可以按類名稱選擇對象並設置數據。這是我的快速解決方案:jsFiddle。您可以修改drag函數以將限制添加到cx位置