问题
I'm using Konvajs, I have group of texts, and I want don't allow drag group outside of the canvas, I'm tried solved that using dragBoundFunc, but that don't help me, now I just try change group position during dragmove, but setPosition, setAbsloutePosition, nothing allow me to change group position
stage.on('dragmove', (e) => stageOnDragMove(e, layer));
const stageOnDragMove = (e: Konva.KonvaEventObject<any>, layer: Konva.Layer) => {
const selectionGroup = layer.findOne('#selection-group');
const transformer = layer.findOne<Konva.Transformer>('Transformer');
if (selectionGroup?.hasName('text-group')) {
const pos = selectionGroup.getClientRect({});
if (pos.x <= 0 || pos.y <= 0) {
selectionGroup.setAbsolutePosition({
x: 0,
y: 0
});
layer.draw();
}
}
transformer.attachTo(selectionGroup);
};
回答1:
You can use this function to limit drag&drop and resize feature to limit its boundaries:
shape.on('dragmove transform', () => {
const box = shape.getClientRect();
const absPos = shape.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;
}
shape.setAbsolutePosition(newAbsPos)
})
Demo: https://jsbin.com/rofupicupu/edit?html,js,output
来源:https://stackoverflow.com/questions/60969263/konvajs-how-to-change-position-of-group-of-texts