我对使用dragBoundFunc
的动态js有一个令人不安的问题。
我在选择器组上定义了dragBoundFunc,它的工作原理非常好,不允许组在绿色矩形上溢出。错误的情况如下:
1-拖动锚点以调整选择器矩形的大小,尝试将锚点拖动到绿色矩形之外。似乎不会超出范围。
2-现在将选择器矩形移到边缘以检查边界。您会看到绿色矩形的位置似乎从其原始位置偏移了。
我该如何解决这种奇怪的行为?有什么想法吗?
Here是小提琴。
group.on("dragend",function(){
var rect = group.get('#rectangle')[0];
var pos = rect.getPosition();
var dx = pos.x;
var dy = pos.y;
group.children.each(function(child){
child.move(-dx, -dy);
});
group.setPosition({
x : pos.x + group.getPosition().x,
y : pos.y + group.getPosition().y
});
layer.draw();
});
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
const group = new Konva.Group({
draggable: true
});
const text1 = new Konva.Text({
x: 10,
y: 15,
text: 'some text 0',
fontSize: 11,
draggable: true,
cursor: 'pointer',
strokeWidth: 0,
stroke: 'rgb(0,0,0)',
wrap: 'none'
});
const text2 = new Konva.Text({
x: 20,
y: 25,
text: 'some text 1',
fontSize: 11,
draggable: true,
cursor: 'pointer',
strokeWidth: 0,
stroke: 'rgb(0,0,0)',
wrap: 'none'
});
group.add(text1);
group.add(text2)
layer.add(group);
const tr = new Konva.Transformer({
node: group
})
layer.add(tr);
let oldX: number;
let oldY: number;
stage.on('dragstart', (e) => {
oldX = e.target.x();
oldY = e.target.y();
});
stage.on('dragmove', (e) => {
const diffX = e.target.x() - oldX;
const diffY = e.target.y() - oldY;
// move everyone
group.children.each((child) => {
// move other nodes
child.x(child.x() + diffX);
child.y(child.y() + diffY);
});
oldX = e.target.x();
oldY = e.target.y();
transformer.attachTo(group);
})
group.on('dragmove transform', () => {
const box = group.getClientRect();
const absPos = group.getAbsolutePosition();
const offsetX = box.x - absPos.x;
const offsetY = box.y - absPos.y;
const newAbsPos = {...absPos}
if (box.x < 0) {
newAbsPos.x = -offsetX;
}
if (box.y < 0) {
newAbsPos.y = -offsetY;
}
if (box.x + box.width > stage.width()) {
newAbsPos.x = stage.width() - box.width - offsetX;
}
if (box.y + box.height > stage.height()) {
newAbsPos.y = stage.height() - box.height - offsetY;
}
group.setAbsolutePosition(newAbsPos)
})
layer.draw();