将圆圈添加到多个路径

时间:2015-01-04 05:53:04

标签: javascript jquery canvas d3.js visualization

您好我正在尝试将小圆圈添加到多个路径线,然后在路径上进行转换。我试图获得路径起点的x pos和y pos但是当我将圆圈附加到它时它会附加到其他位置。如果您能告诉我如何将圆圈附加到路径开始然后将其转换为路径末尾,我将非常感谢您的帮助。 以下是jsfiddle http://jsfiddle.net/4rsr098o/

<!DOCTYPE html>
 <meta charset="utf-8">
 <title></title>
<style>

body {
background: #012;
}

path {
fill: none;
stroke: white;
stroke-opacity: .5;
 stroke-width: 5;
}

</style>
<body>
 <script src="js/libs/d3/d3.v3.js"></script>
<script>

var width = 3260,
height = 3500;
var StartPos;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
 .append("g")
 .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var gradient = svg.append("defs").append("linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "20%")
.attr("x2", "20%")
.attr("y2", "100%");

 gradient.append("stop")
.attr("offset", "20%")
.attr("stop-color", "#ccf");

 gradient.append("stop")
.attr("offset", "50%")
.attr("stop-color", "#1C425C");

 gradient.append("stop")
.attr("offset", "100%")
.attr("stop-color", "#19162B");



 // could use transparent gradient overlay to vary raindrop color
 var path1=svg.selectAll("path")
.data(d3.range(15))
.enter().append("path")

.attr("d", function(d) { return raindrop(d); })
 .attr("transform", function(d) {
 return "rotate(" + d + ")"
     + "translate(" + (d) + ",0)"
    + "rotate(90)";
 });


function raindrop(size) {
 // console.log(size);
var r = 100+10*size;

  return "M" + r + ","+ -size*4
 + "C" + -(90-22*size) + "," + -(90-10*size) + " 0," + -470 + " 200," + -(600+size*4);



};

  var pathEl ;
test();
function test(){

pathEl = svg.selectAll("path").each(function(d,i){
var test= this.getTotalLength();  
StartPos=this.getPointAtLength(0);
var EndPos=this.getPointAtLength(test);
console.log(test);
console.log("("+StartPos.x+","+StartPos.y+")");
console.log("("+EndPos.x+","+EndPos.y+")");
addCircle();
});
}
function addCircle(){
       svg.append("circle")
    .attr("opacity", 1)
    .attr("cx", StartPos.x)
    .attr("cy", StartPos.y)
.attr("r", 4)
    .attr("fill", "white");
  }
</script>

1 个答案:

答案 0 :(得分:1)

您的代码基本上是正确的,除非您已经对您不适用于您的圈子的路径应用了额外的转换:

.attr("transform", function(d) {
    return "rotate(" + d + ")" + "translate(" + (d) + ",0)" + "rotate(90)";
});

这里有一些快速编辑,可以将圆圈放在路径的开头:

function test() {
  svg.selectAll("path").each(function(d, i) {
    var trans = d3.select(this).attr("transform");
    var totLength = this.getTotalLength();
    pos = this.getPointAtLength(0);
    addCircle(pos, trans);
  });
}

function addCircle(pos, trans) {
  svg.append("circle")
    .attr("opacity", 1)
    .attr("cx", pos.x)
    .attr("cy", pos.y)
    .attr("transform", trans)
    .attr("r", 4)
    .attr("fill", "white");
}

示例here