如何通过一个起点来旋转一个栏?
我想旋转绿色矩形条以指向圆圈的中心如何操作。
以下代码是我绘制矩形的方法。
downNode = downNode
.data(_nodes)
.attr("id", function (d, i) {
return "nodeDown" + d.dbId;
})
.enter()
.append("rect")
.attr("class", "node").attr("class","downExpressed")
.attr("x", function (d) {
return Math.sin( Math.PI - (Math.max(0, Math.min(2 * Math.PI, x(d.dx)))+ Math.max(0, Math.min(2* Math.PI, x(d.dx + d.d_dx)))) / 2 ) * Math.max(0, y(d.dy+ d.d_dy)); })
.attr("height", function (d) {
var thea = Math.max(0, Math.min(2 * Math.PI, x(d.dx + d.d_dx))) - Math.max(0, Math.min(2 * Math.PI, x(d.dx)));
var r = Math.max(0, y(d.dy));
return Math.min(r * thea, Math.floor(_this.maxLevel));})
.attr("y", function (d) {
return Math.cos(Math.PI - (Math.max(0, Math.min(2 * Math.PI, x(d.dx)))+ Math.max(0, Math.min(2 * Math.PI, x(d.dx + d.d_dx)))) / 2) * Math.max(0, y(d.dy+ d.d_dy));})
.attr("width", function (d) {
return 1/2*Math.floor((d.expression.downs.length) / DownMax * ( Math.max(0, y(d.dy + d.d_dy)) - Math.max(0, y(d.dy)) ));
})
首先我计算角度和r,然后通过r cos(thea)y位置r sin(thea)得到x位置;
但结果并未指向中心,我需要将其旋转到矩形条的起点。
任何建议,谢谢。
答案 0 :(得分:0)
我不知道你有什么限制,所以我会展示两种可能的解决方案:
1-你可以在圆圈的中间设置rect元素的锚点(使用变换attr)并围绕该点旋转。
2-如果你不想用变换设置锚点,你必须做一些矢量计算。
第一个例子: 在jfiddle http://jsfiddle.net/ym5w0gk5/1/
svg.append("rect")
.attr("id","myRect")
.attr("width",30).attr("height",10)
//this is the relative position to the anchor point
.attr("x",-80).attr("y",-5)
//with the transform attribute you define anchor point (translate)
// and the rotation (rotation). change rotation to make it go around the center.
.attr("transform","translate("+width/2+","+height/2+")rotate("+rotate+")");
第二个例子:下一个例子是一个矩形的拖动函数,它总是面向一个点。
您可以在jsfiddle http://jsfiddle.net/denimad/shn1u02n/
中找到它...
//setup of the draggable rectangle
var drag = d3.behavior.drag().on("drag", dragmove);
svg.append("rect").attr("width",10).attr("height",30).call(drag);
...
function dragmove(d) {
//get mouse coordinates
var x = d3.event.x;
var y = d3.event.y;
//get the vector (V1) between the mouse coordinates and anchor point coordinates
V1 ={"x": x-anchorPoint.x,"y":-(y-anchorPoint.y)};
//get the perpendicular vector (V2) . If you have a vector v with coordinates (x, y), then a vector perpendicular to v is (y, -x) or (-y, x).
V2 ={"x": auxvect.x,"y":-auxvect.y)};
//get the angle between vector (0,1) and V2 .
//http://stackoverflow.com/questions/12903547/fastest-way-to-find-the-angle-between-two-points
ang= Math.acos( V2.x / Math.sqrt(V2.x*auxvect.x + V2.y*V2.y) );
ang = ang * 180 / Math.PI; //in degrees
//finally, this is the rotation angle to apply in the transformation
if(y<anchorPoint.y){
d3.select(this).attr("transform", "translate(" + x + "," + y + ")rotate("+(-ang)+")");
}else{
d3.select(this).attr("transform", "translate(" + x + "," + y + ")rotate("+(ang)+")");
}
}