问题描述
整天炒完脑后。终于决定在这里问。
我正在尝试在d3.js的弧线末尾添加文本。我尝试使用arc.cenriod(),但是将文本保留在弧的中心。我想在圆弧的末尾显示文本。
After Frying my brain all day. Finally decided to ask here.I am trying to append a text at the end of the arc in d3.js. I tried using arc.cenriod() but that keeps the text in the center of the arc. I want to display the text at the end of the arc.
var pi = Math.PI, width=600, height=400; var iR=150; var oR=110;
startAngle = 90, endAngle = 270, innerRad=150 , outerRad=110 ;
var new_color, hold; var max = 300, min = 0, current = 0;
var cur_color = 'limegreen';
var firstValue = 100;
var arc = d3.svg.arc().innerRadius(iR).outerRadius(oR).startAngle(-120 * (pi/180));
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
var nScale = d3.scale.linear()
.range([0, 240])
.domain([0,300]);
var current = svg.append("text").attr("transform", "translate(0,"+ (iR/2) +")")
.attr("text-anchor", "middle").style("font-size", "50").style("font-family", "Helvetica").text(current)
var background = svg.append("path").datum({endAngle: 120 * (pi/180)}).style("fill", "none").attr("d", arc);
setInterval(function() {
var dataRead =Math.random()*300 ;
var num = nScale(dataRead);
var numPi = Math.floor(num - 119) * (pi/180);
current.transition().text(Math.floor(dataRead));
background
.transition()
.duration(1000)
.style("fill", "limegreen").call(arcTween, numPi);
}, 2000);
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
var interpolate = d3.interpolate(d.endAngle, newAngle);
return function(t) {
d.endAngle = interpolate(t);
; return arc(d);
};
});
}
这是上面代码的jsfiddle。
Here is my jsfiddle for the above code. http://jsfiddle.net/chaitugoli/duo29t5k/
我想让current(文本元素)与尖端的弧线一起移动。
如何获取圆弧末端的坐标。
There I want the current(text element) to move along with the arc at the tip.How can i get the co-ordinates of the end of the arc.
请告诉我。任何建议都会对
有帮助(如果您在js小提琴中看不到任何东西,则可能是d3 import的问题。如果需要,请在本地系统上尝试)
Please let me know. Any suggestions would help(if you dont see any thing in the js fiddle , it probably might be the issue of the d3 import . please try it on your local system if you want to)
谢谢
推荐答案
我将直接解析路径并从中获取信息:
I'd parse the path directly and get the information from that:
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
var interpolate = d3.interpolate(d.endAngle, newAngle);
return function(t) {
d.endAngle = interpolate(t);
var path = arc(d);
var coords = path.split("L")[1].split("A")[0]; //<-- this is the position of the end of the line connecting the two arcs
current.attr('transform', 'translate(' + coords + ')' + 'rotate(' + (d.endAngle * 180/Math.PI) + ')'); //<-- position text and rotate it
return path;
};
});
}
已更新。
这篇关于在d3.js中的弧线末端显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!