我想让一个svg元素(path,rect或circle)能够被拖动并给它调整大小句柄。
但与HTML DOM不同,并非所有元素都有左上角x,y坐标以及围绕内容的框的宽度和高度。这使得制作通用的调整大小或拖动过程变得不方便。
将每个路径或圆圈绘制在自己的svg对象中以给我一个可以玩的方框是不是一个好主意?
如何在SVG中实现可拖动/可调整大小?
答案 0 :(得分:53)
注意:对于拖动和调整大小,您必须为某些不同类型的元素单独创建案例。看一下处理在同一组函数中拖动椭圆和矩形的 the example I provide later on 。
要使元素可拖动,请使用:
element.drag(move, start, up);
这三个参数是对处理移动(拖动),启动(鼠标按下)和停止(mouseup)的函数的引用。
例如,制作一个可拖动的圆圈(来自文档):
window.onload = function() {
var R = Raphael("canvas", 500, 500);
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: .5});
};
c.drag(move, start, up);
};
在上面的示例中,ox
和oy
属性被添加到元素以跟踪其位置,这些属性与dx
和{{1}一起使用用于在被拖动时更改元素的位置。
A more complicated drag and drop 回答 this question 。
要使对象可调整大小,您只需为缩放器创建第二组拖放方法,然后根据拖动缩放器调整目标元素dy
和height
。
这里写了一个完整的拖放和可调整大小的框:
width
包含的事件处理程序(您当然可以将更多内容与 .node()
结合使用),拖放说明位于页面底部 {{3} } 强>
你只需制作一个拉斐尔画布,然后每个项目都是不同的元素。只需将它们分配给变量就可以处理它们,就像上面的示例一样(window.onload = function() {
var R = Raphael("canvas", 500, 500),
c = R.rect(100, 100, 100, 100).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
cursor: "move"
}),
s = R.rect(180, 180, 20, 20).attr({
fill: "hsb(.8, .5, .5)",
stroke: "none",
opacity: .5
}),
// start, move, and up are the drag functions
start = function () {
// storing original coordinates
this.ox = this.attr("x");
this.oy = this.attr("y");
this.attr({opacity: 1});
this.sizer.ox = this.sizer.attr("x");
this.sizer.oy = this.sizer.attr("y");
this.sizer.attr({opacity: 1});
},
move = function (dx, dy) {
// move will be called with dx and dy
this.attr({x: this.ox + dx, y: this.oy + dy});
this.sizer.attr({x: this.sizer.ox + dx, y: this.sizer.oy + dy});
},
up = function () {
// restoring state
this.attr({opacity: .5});
this.sizer.attr({opacity: .5});
},
rstart = function () {
// storing original coordinates
this.ox = this.attr("x");
this.oy = this.attr("y");
this.box.ow = this.box.attr("width");
this.box.oh = this.box.attr("height");
},
rmove = function (dx, dy) {
// move will be called with dx and dy
this.attr({x: this.ox + dx, y: this.oy + dy});
this.box.attr({width: this.box.ow + dx, height: this.box.oh + dy});
};
// rstart and rmove are the resize functions;
c.drag(move, start, up);
c.sizer = s;
s.drag(rmove, rstart);
s.box = c;
};
用于引用创建的圆形元素)。
在回复评论时,这是一个简单的拖放+调整大小的圆圈。诀窍在于圈子使用属性c
和cx
进行定位,使用cy
进行大小调整。机制几乎相同......椭圆会稍微复杂一些,但同样只是处理正确属性的问题。
r
答案 1 :(得分:4)
看看Raphael.FreeTransform似乎正在做你想要的事情。
答案 2 :(得分:3)
在这里尝试Graphiti是链接:Draw2d and Graphiti
它基于Raphael,非常易于使用。
答案 3 :(得分:0)
还有SVG.js插件。