我正在使用 KineticJS 开发一个简单的绘图程序。我必须实现的是用鼠标移动绘制一个矩形、直线或圆形,并且绘制的形状可以通过鼠标拖动或调整大小。我的问题是,我必须使用mousedown
和mousemove
事件来绘制,但我不能同时实现拖放或调整大小。
这是我的绘图代码:
stage.on("mousedown", function() {
if ((drawFlag == 1) && (dragFlag == 0)) {
if (moving) {
moving = false;
layer.draw();
} else {
var mousePos = stage.getMousePosition();
line = new Kinetic.Line({
points: [0, 0, 50, 50],
stroke: "red"
});
layer.add(line);
line.getPoints()[0].x = mousePos.x;
line.getPoints()[0].y = mousePos.y;
line.getPoints()[1].x = mousePos.x;
line.getPoints()[1].y = mousePos.y;
moving = true;
layer.drawScene();
}
}
if ((drawFlag == 2) && (dragFlag == 0)) {
if (moving) {
moving = false;
layer.draw();
} else {
var mousePos = stage.getMousePosition();
rect = new Kinetic.Rect({
x: 20,
y: 20,
fill: "red",
stroke: "black",
strokeWidth: 2,
draggle: true,
width: 0,
height: 0
});
rect.setX(mousePos.x);
rect.setY(mousePos.y);
rect.setWidth(0);
rect.setHeight(0);
moving = true;
layer.drawScene();
layer.add(rect);
Rects.push(rect);
}
}
});
stage.on("mousemove", function() {
if ((drawFlag == 1) && (dragFlag == 0)) {
if (moving) {
var mousePos = stage.getMousePosition();
var x = mousePos.x;
var y = mousePos.y;
line.getPoints()[1].x = mousePos.x;
line.getPoints()[1].y = mousePos.y;
moving = true;
layer.drawScene();
}
}
if ((drawFlag == 2) && (dragFlag == 0)) {
if (moving) {
var mousePos = stage.getMousePosition();
var x = mousePos.x;
var y = mousePos.y;
rect.setWidth(mousePos.x - rect.getX());
rect.setHeight(mousePos.y - rect.getY());
moving = true;
layer.drawScene();
}
}
});
stage.on("mouseup", function() {
moving = false;
});
绘制一个矩形后,当我点击它时,它应该是用鼠标移动来拖动的。但是,在我的程序中,单击绘制的矩形会导致绘制另一个矩形而不是拖动它。所以我尝试使用一个dragFlag来指示我是在绘制还是在拖动。我使用一个函数来检查鼠标光标是否在任何绘制的矩形上:
for (var n = 0; n < Rects.length; n++) {
(function() {
Rects[n].on('mouseover', function() {
dragFlag = 1;
document.body.style.cursor = "pointer";
});
Rects[n].on('mouseout', function() {
dragFlag = 0;
document.body.style.cursor = "default";
});
if (dragFlag == 1) {
Rects[n].on("dragstart", function() {
Rects[n].moveToTop();
layer.draw();
});
Rects[n].on("dragmove", function() {
document.body.style.cursor = "pointer";
});
}
});
但这行不通。无法检查鼠标光标的位置,因此我在单击绘制的矩形时仍在绘制新的矩形。任何人都知道如何通过鼠标移动来实现绘图,并在绘制的形状上拖放?
我感谢您的帮助。