d3.js节点和链接

我试图让节点连接到线,并能拖动时移动。 我知道我需要一个鼠标,鼠标,鼠标和鼠标。 但是,我不知道如何使用d3.js来做到这一点,因为我从来没有做过。 这是我迄今为止所做的。

window.onload = function () { var drawOptions = { // dimensions of svg element SVG_WIDTH: 800, SVG_HEIGHT: 600, SHRINK_FACTOR: 100, BIG_CIRCLE: 200 }; // 1. array of objects representing the network // each object is a province or state // preliminary version - only 2 provinces, 1 state var provincesAndStates = [ { name: 'Ontario', sym: 'ON', country: 'Canada', pop: 13873933 }, { name: 'Quebec', sym: 'QC', country: 'Canada', pop: 8294656 }, { name: 'New York', sym: 'NY', country: 'USA', pop: 19795791 }, { name: 'Michigan', sym: 'MI', country: 'USA', pop: 30795791 }, { name: 'Georgia', sym: 'GA', country: 'USA', pop: 20795791 }, { name: 'Alabama', sym: 'Al', country: 'USA', pop: 1700000 }, { name: 'California', sym: 'CA', country: 'USA', pop: 2000000 }, { name: 'Florida', sym: 'Fl', country: 'USA', pop: 2500000 }, { name: 'Texas', sym: 'TX', country: 'USA', pop: 3100000 }, { name: 'Tenesse', sym: 'TN', country: 'USA', pop: 7000000 }, { name: 'Newfoundland', sym: 'NFL', country: 'USA', pop: 1600000 } ]; var connections = [ { source: 'ON', target: 'QC' }, { source: 'ON', target: 'NY' }, { source: 'QC', target: 'NY' }, { source: 'TN', target: 'NFL' }, { source: 'Al', target: 'GA' } ]; d3.select('#graphicsContainer') .append('svg') .attr('width', drawOptions.SVG_WIDTH) .attr('height', drawOptions.SVG_HEIGHT); // Circle d3.select('svg').selectAll('circle').data(provincesAndStates).enter().append('circle') .attr('id', function (d, i) { return provincesAndStates[i].sym }); d3.select('svg').selectAll('circle') .attr('r', function (d, i) { return Math.sqrt(d.pop) / drawOptions.SHRINK_FACTOR }) .attr('cx', function (d, i) { return drawOptions.SVG_WIDTH / 2 + drawOptions.BIG_CIRCLE * Math.sin(i * 2 * Math.PI / provincesAndStates.length); }) .attr('cy', function (d, i) { return drawOptions.SVG_HEIGHT / 2 + drawOptions.BIG_CIRCLE * Math.cos(i * 2 * Math.PI / provincesAndStates.length); }) d3.select('svg').selectAll('line').data(connections).enter().append('line') .attr('id', function (d, i) { return d.source + '-' + d.target }); d3.select('svg').selectAll('line') .attr('x1', function (d, i) { var srcCircle = d3.select('#' + d.source); return srcCircle.attr('cx'); }) .attr('y1', function (d, i) { var srcCircle = d3.select('#' + d.source); return srcCircle.attr('cy'); }) .attr('x2', function (d, i) { var tgtCircle = d3.select('#' + d.target); return tgtCircle.attr('cx'); }) .attr('y2', function (d, i) { var tgtCircle = d3.select('#' + d.target); return tgtCircle.attr('cy'); }) // DRAGGINGCIRCLES d3.selectAll('circle').call(d3.drag().on('drag', dragCircle)); function dragCircle(d) { var thisCircle = d3.select(this); thisCircle.attr('cx', d3.event.x).attr('cy', d3.event.y); } };