Gui*_*rmo 12 javascript graphics svg raphael
我有这个简单的虚拟文件,我正在用它做一些测试.预期的结果是沿路径拖动红色圆圈.问题是我无法弄清楚如何关联两个形状.
<!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>
Run Code Online (Sandbox Code Playgroud)
fuz*_*zic 29
您没有准确指定您希望交互如何工作,所以我使用了对我来说最自然的东西.
我们可以假设点必须保留在路径上,因此它的位置必须由
p.getPointAtLength(l);
Run Code Online (Sandbox Code Playgroud)
对于一些l.要找到l我们可以搜索曲线和光标位置之间的距离的局部最小值.我们初始化搜索,l0其中where l0是l 当前定义点位置的值.
有关工作示例,请参阅此处的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);?
Run Code Online (Sandbox Code Playgroud)
圆形对象的中心有一个 x,y 坐标,还有一个半径。要确保圆保持在直线上,只需找到圆心与直线本身的交点即可。
为此,您需要存储线条的起点和终点坐标。然后使用直线方程:y = mx + b,您可以找到斜率和 y 截距。一旦有了直线的函数,您就可以通过插入不同的 x 值来生成圆的新坐标。
另外,通过将圆的 x,y 坐标插入函数中,您可以检查圆是否在线上。
| 归档时间: |
|
| 查看次数: |
5852 次 |
| 最近记录: |