第一次写博客,写的不好勿怪!!! 此博客是通过d3 v4 实现一个饼状图,并添加了折线标注;代码如下 let self = this; var tooltip = d3.select("body").append("div").attr("class", "toolTip"); let ele = document.getElementById(this.svg); var svg = d3.select("#"+this.svg), width = +ele.clientWidth, height = +ele.clientHeight, radius = Math.min(width-80, height-80) / 2, g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + (height/2) + ")"); /*console.log("width:"+ele.clientWidth); console.log("heigth:"+ele.clientHeight);*/ var color = d3.scaleOrdinal(["#74F590", "#F56464", "#64BCF5"]); var pie = d3.pie() .sort(null) .value(function(d) { return d.value; }); var path = d3.arc() .outerRadius(radius) .innerRadius(35); var path0 = d3.arc() .outerRadius(radius+10) .innerRadius(35); var label = d3.arc() .outerRadius(radius - 20) .innerRadius(radius - 20); var label0 = d3.arc() .outerRadius(radius + 20) .innerRadius(radius + 20); let data = [ {"area": "正在运行 ", "value": 2704659}, {"area": "异常终止 ", "value": 4499890}, {"area": "已完成", "value": 2159981} ]; var arc = g.selectAll(".arc") .data(pie(data)) .enter().append("g") .attr("class", "arc"); arc.on("mouseover",function(d,i){ d3.select(this).select("path") .attr("d",path0); tooltip .style("left", d3.event.pageX - 50 + "px") .style("top", d3.event.pageY - 70 + "px") .style("display", "inline-block") .html( " "+ " " ); }); arc.on("mouseout",function(d,i){ d3.select(this).select("path") .attr("d",path); tooltip.style("display", "none"); }); arc.append("path") .attr("d", path) .attr("fill", function(d) { return color(d.data.area); }); arc.append("text") .attr("transform", function(d) { var x2 =label0.centroid(d)[0]; var y2 =label0.centroid(d)[1]; var x3 = x2<0?x2-70:x2+30; return "translate(" + x3 + "," + y2 + ")"; }) .attr("dy", "0.35em") .text(function(d) { return d.data.area; }); arc.append("polyline") .attr("points",function(d){ var x1 =label.centroid(d)[0]; var y1 =label.centroid(d)[1]; var x2 =label0.centroid(d)[0]; var y2 =label0.centroid(d)[1]; var x3 = x2<0?x2-30:x2+30; return x3+","+y2+" "+x2+","+y2+" "+x1+","+y1; }) .style("fill","none") .style("stroke","rgb(99,99,99)") .style("stroke-width","1")