gpt4 book ai didi

javascript - 如何沿给定路径拖动形状

转载 作者:可可西里 更新时间:2023-11-01 01:57:30 25 4
gpt4 key购买 nike

我有这个简单的虚拟文件,我用它来做一些测试。预期结果是沿着路径拖动红色圆圈。问题是我不知道如何关联这两种形状。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="raphael-min.js"></script>
</head>
<body>
<script type="text/javascript">
// Creates canvas 320 × 200 at 10, 50
var r = Raphael(10, 50, 320, 200);

var p = r.path("M100,100c0,50 100-50 100,0c0,50 -100-50 -100,0z").attr({stroke: "#ddd"}),
e = r.ellipse(104, 100, 4, 4).attr({stroke: "none", fill: "#f00"}),


/*var c = r.circle(100, 100, 50).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5
});*/


var start = function () {
// storing original coordinates
this.ox = this.attr("cx");
this.oy = this.attr("cy");
this.attr({opacity: 1});
},
move = function (dx, dy) {
// move will be called with dx and dy
this.attr({cx: this.ox + dx, cy: this.oy + dy});
},
up = function () {
// restoring state
this.attr({opacity: 1});
};
e.drag(move, start, up);
</script>
</body>
</html>

最佳答案

您没有具体说明您希望交互如何工作,所以我使用了我觉得最自然的方式。

我们可以假设点必须留在路径上,所以它的位置必须由下式给出

p.getPointAtLength(l);

对于一些 l。要找到 l,我们可以搜索曲线和光标位置之间距离的局部 最小值。我们使用 l0 初始化搜索,其中 l0l currently 的值,定义了点的位置。

请参阅此处的 JSfiddle 以获取工作示例:

http://jsfiddle.net/fuzic/kKLtH/

代码如下:

var searchDl = 1;
var l = 0;

// Creates canvas 320 × 200 at 10, 50
var r = Raphael(10, 50, 320, 200);

var p = r.path("M100,100c0,50 100-50 100,0c0,50 -100-50 -100,0z").attr({stroke: "#ddd"}),
pt = p.getPointAtLength(l);
e = r.ellipse(pt.x, pt.y, 4, 4).attr({stroke: "none", fill: "#f00"}),
totLen = p.getTotalLength(),


start = function () {
// storing original coordinates
this.ox = this.attr("cx");
this.oy = this.attr("cy");
this.attr({opacity: 1});
},
move = function (dx, dy) {
var tmpPt = {
x : this.ox + dx,
y : this.oy + dy
};
l = gradSearch(l, tmpPt);
pt = p.getPointAtLength(l);
this.attr({cx: pt.x, cy: pt.y});
},
up = function () {
this.attr({opacity: 1});
},
gradSearch = function (l0, pt) {
l0 = l0 + totLen;
var l1 = l0,
dist0 = dist(p.getPointAtLength(l0 % totLen), pt),
dist1,
searchDir;

if (dist(p.getPointAtLength((l0 - searchDl) % totLen), pt) >
dist(p.getPointAtLength((l0 + searchDl) % totLen), pt)) {
searchDir = searchDl;
} else {
searchDir = -searchDl;
}

l1 += searchDir;
dist1 = dist(p.getPointAtLength(l1 % totLen), pt);
while (dist1 < dist0) {
dist0 = dist1;
l1 += searchDir;
dist1 = dist(p.getPointAtLength(l1 % totLen), pt);
}
l1 -= searchDir;

return (l1 % totLen);
},
dist = function (pt1, pt2) {
var dx = pt1.x - pt2.x;
var dy = pt1.y - pt2.y;
return Math.sqrt(dx * dx + dy * dy);
};
e.drag(move, start, up);​

关于javascript - 如何沿给定路径拖动形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7406021/

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