在此jsFiddle中,我有一个带有线/路径的Raphael画布,用户可以在其中拖动它。
问题是,鼠标指针的确切顶部像素必须在线上才能拖动它。我需要拉斐尔更加“原谅”,并让用户拖动线条(如果它触摸到指针的顶部,例如3像素)。
我添加了mouseover/mouseout
事件以实际上告诉鼠标何时在直线上,否则很难知道。
所以问题是:有没有一种方法可以拖动线条而不必精确定位鼠标指针?
var paper = Raphael("canvas", 600, 600);
var line = this.paper.path('M10 10 L50 50');
var start = function () {
this.odx = 0;
this.ody = 0;
},
move = function (dx, dy) {
this.translate(dx - this.odx, dy - this.ody);
this.odx = dx;
this.ody = dy;
},
up = function () {};
line.drag(move, start, up);
line.mouseover(function(e) {
line.attr('stroke', 'red');
});
line.mouseout(function(e) {
line.attr('stroke', 'black');
});
Raphael库出于绘图目的创建了SVG元素(而不是CANVAS元素),而绘图线在SVG元素内创建了PATH元素。
我通过增加悬停线的宽度获得了一些成功。您必须通过至少将鼠标移到该线上来触发宽度更改,但是之后选择起来要容易得多。尽管所产生的视觉效果可能并不完美(可能会发生一些宽度滑动),但继续进行拖动操作不会出现问题。
您可以通过在stroke-width
和mouseover
处理程序中修改mouseout
属性来尝试增加线宽:
line.mouseover(function(e) {
line.attr('stroke', 'red');
line.attr('stroke-width', '9')
});
line.mouseout(function(e) {
line.attr('stroke', 'black');
line.attr('stroke-width', '1')
});
或通过使用[]悬停在CSS中的所有路径元素上时修改stroke-width
样式
path:hover {
stroke-width: 9;
}
mouseover
光标的类名称draggable
来增加move
上的行的宽度,draggable
替换为dragging
(这消除了宽度增加),并在svg容器上设置了move
光标,draggable
上的类别dragging
,但不删除mouseout
up
函数中的光标。"use strict";
var container = document.getElementById("canvas");
var paper = Raphael("canvas", 600, 600);
var line = this.paper.path('M10 10 L50 50');
var start = function () {
this.odx = 0;
this.ody = 0;
},
move = function (dx, dy) {
this.translate(dx - this.odx, dy - this.ody);
this.odx = dx;
this.ody = dy;
if( this.node.classList.contains("draggable")) {
this.node.classList.replace("draggable", "dragging");
container.classList.add("moveCursor");
}
},
up = function (e) {
line.node.classList.remove("draggable", "dragging");
container.classList.remove("moveCursor");
};
line.drag(move, start, up);
line.mouseover(function(e) {
if(!e.target.classList.contains("dragging")) {
e.target.setAttribute("class", "draggable");
}
});
.draggable:hover {
stroke-width: 9;
stroke:red;
cursor: move;
}
path.dragging {
stroke: red;
}
.moveCursor{
cursor:move;
}
svg {
border: thin solid blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<!-- body-html -->
<div id="canvas"></div>
该代码基本上是用于演示-如果将线拖动到SVG元素外部,则看不到它或抓住它将其拖动回去。
某些CSS规则(例如path.dragging
)需要更多的特殊性,才能优先于Raphael提供的默认设置。