Reputation: 151
I'm trying to draw a rectangle on an image with React Konva, and get the coordinate of its 4 corners. I have calculated and return the coordinate of 4 corners quite accurately but the problem is I still couldn't implement the dragBoundFunc (to bound the rectangle in the canvas when dragging) and the boundBoxFunc (to bound the rectangle in the canvas when transform (rotate, scale)).
One solution I can think of is get the min and max X,Y coordinate of 4 corners, then if the min < 0 and the max > dimension of the canvas then return false. However I still have not managed to do it, you can checkout my sandbox here. Thanks for your help.
Upvotes: 3
Views: 2431
Reputation: 20373
For dragging functionality you can do this:
shape.on('dragmove', () => {
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)
});
The idea above is just to limit absolute position of a node.
For transforming is a bit more complex and may require polishing for smooth work. But I tried this:
let oldAttrs;
shape.on('transform', () => {
const box = shape.getClientRect();
const isOut = box.x < 0 || box.y < 0 || box.x + box.width > stage.width() || box.y + box.height > stage.height();
if (isOut) {
shape.setAttrs(oldAttrs);
} else {
oldAttrs = {...shape.getAttrs()};
}
});
So if the position of shape is out of visible viewport we just need to reset attributes back to previous values.
Demo: https://jsbin.com/gakelemuru/2/edit?js,output
Upvotes: 4