gpt4 book ai didi

javascript - 在 D3 图中绕轴旋转矩形

转载 作者:行者123 更新时间:2023-11-30 16:29:12 24 4
gpt4 key购买 nike

我正在尝试获取一个在所有 Angular 上都有四个 handle 的矩形,以按所需的 Angular 旋转矩形。有人可以帮助我如何在拖动 handle 时在其轴上旋转矩形吗?

我确实找到了一个椭圆的示例,并且尝试将其修改为矩形,但没有成功。

var w = 400,
h = 400,
data = {
x: 150,
y: 100,
rx: 50,
ry: 50,
angle: 0
};

// Returns radians
function angleBetweenPoints(p1, p2) {
if (p1[0] == p2[0] && p1[1] == p2[1])
return Math.PI / 2;
else
return Math.atan2(p2[1] - p1[1], p2[0] - p1[0] );
}

function distanceBetweenPoints(p1, p2) {
return Math.sqrt( Math.pow( p2[1] - p1[1], 2 ) + Math.pow( p2[0] - p1[0], 2 ) );
}

var svg = d3.select("body")
.append("svg")
.attr("width", 400)
.attr("height", 300);

var group = svg.append("svg:g").attr('id' , 'id123');


var handles = group.selectAll("circle")
.data([
{x:data.x, y:data.y + data.ry, name:"n"},
{x:data.x + data.rx, y:data.y, name:"e"},
{x:data.x, y:data.y - data.ry, name:"s"},
{x:data.x - data.rx, y:data.y, name:"w"}
], function (d) { return d.name; })
.enter()
.append("svg:circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", 6.5)
.call(d3.behavior.drag()
.on("drag", function (d) {
// Resizing

var exy = [d3.event.x, d3.event.y],
dxy = [data.x, data.y],
dist = distanceBetweenPoints(exy, dxy),
angle = data.angle + angleBetweenPoints(dxy, exy);
switch(d.name) {
case "e":
case "w":
break;
case "s":
case "n":
angle += Math.PI/2;
break;
};
data.angle = angle;
update();
})
);

var ellipse = group.append("svg:ellipse");

function toDegrees(rad) {
return rad * (180/Math.PI);
}

function update() {
ellipse
.attr("cx", data.x)
.attr("cy", data.y)
.attr("rx", data.rx)
.attr("ry", data.ry);

group.attr("transform", "rotate(" + toDegrees(data.angle) + "," + data.x + "," + data.y + ")");

}

update();

http://jsfiddle.net/roug3/hon4kxp6/2/

最佳答案

首先你制作一个矩形

var rect = group.append("svg:rect");

然后相应地放置矩形。

//place the rectangle in its place
function update() {
rect
.attr("x", data.x - data.rx +5)//the x coordinate
.attr("y", data.y - data.ry +5)
.attr("width", (data.rx*2)-10)//the width
.attr("height", (data.ry*2)-10);//the height

group.attr("transform", "rotate(" + toDegrees(data.angle) + "," + data.x + "," + data.y + ")");

}

工作代码here

矩形旋转的工作代码here

希望这有帮助!

关于javascript - 在 D3 图中绕轴旋转矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com