svg: How to set a circle on the calculated line?

2019-04-11 10:02发布

问题:

I'm trying to set a circle on the calculated line with svg.

Here is my the example: http://jsfiddle.net/7XC9j/

html:

<svg width="300" height="500">
  <g id="g-1"></g>
</svg>

javascript:

var line = d3.svg.line()
  .x(function(d) { return d.x; })
  .y(function(d) { return d.y; })
  .interpolate("cardinal")
  .tension(0);

 var points = [{x: 0, y: 200}, {x: 25, y: 180}, {x: 50, y: 150}, {x: 100, y: 145}, {x: 200, y: 130}, {x: 300, y: 120}, {x: 500, y: 25}];

 d3.select("#g-1").append("path").attr("d", line(points));

and now I try to set the circle (depends of X to the line), however I look for some function like line(myX).x for drawing the circle:

 d3.select("#g-1").append("svg:circle")
    .attr("cx", myX)
    .attr("cy", line(myX).x)
    .attr("r", 4.5);

回答1:

You can do it with path.getPointAtLength(i)

see http://jsfiddle.net/GQ8WJ/



回答2:

Here is one method for adding a circle that uses the 4th object in the points array.

Working fiddle here:
http://jsfiddle.net/3RumJ/

JavaScript

d3.select("#g-1")
    .append("circle")
    .attr("cx", points[3].x )
    .attr("cy", points[3].y )
    .attr("r", 4.5);


回答3:

I think this will be solution: http://jsfiddle.net/amgq3/ In this example I take x from 0 to 500 and use function line to get required y