Reputation: 839
I am trying to create a multiple shape selection using Transformer
of React konva
. It is working well with the mouse click on one shape and then to other shape, creates a whole selection of both shapes. i want this to be achieved by mouse drag and drop. for which i wrote mouse up,down and move and click functions on stage which are mentioned in the documentation. there is no errors but mouse drag selection is not working. I want the selection to work exactly same as given on documentation demo.
Here is my demo sandbox link.
Upvotes: 0
Views: 2190
Reputation: 20288
There are many ways to do that. My way:
const selectionRectRef = React.useRef();
const selection = React.useRef({
visible: false,
x1: 0,
y1: 0,
x2: 0,
y2: 0
});
const updateSelectionRect = () => {
const node = selectionRectRef.current;
node.setAttrs({
visible: selection.current.visible,
x: Math.min(selection.current.x1, selection.current.x2),
y: Math.min(selection.current.y1, selection.current.y2),
width: Math.abs(selection.current.x1 - selection.current.x2),
height: Math.abs(selection.current.y1 - selection.current.y2),
fill: "rgba(0, 161, 255, 0.3)"
});
node.getLayer().batchDraw();
};
const oldPos = React.useRef(null);
const onMouseDown = (e) => {
const isElement = e.target.findAncestor(".elements-container");
const isTransformer = e.target.findAncestor("Transformer");
if (isElement || isTransformer) {
return;
}
const pos = e.target.getStage().getPointerPosition();
selection.current.visible = true;
selection.current.x1 = pos.x;
selection.current.y1 = pos.y;
selection.current.x2 = pos.x;
selection.current.y2 = pos.y;
updateSelectionRect();
};
const onMouseMove = (e) => {
if (!selection.current.visible) {
return;
}
const pos = e.target.getStage().getPointerPosition();
selection.current.x2 = pos.x;
selection.current.y2 = pos.y;
updateSelectionRect();
};
const onMouseUp = () => {
oldPos.current = null;
if (!selection.current.visible) {
return;
}
const selBox = selectionRectRef.current.getClientRect();
const elements = [];
layerRef.current.find(".rectangle").forEach((elementNode) => {
const elBox = elementNode.getClientRect();
if (Konva.Util.haveIntersection(selBox, elBox)) {
elements.push(elementNode);
}
});
trRef.current.nodes(elements);
selection.current.visible = false;
// disable click event
Konva.listenClickTap = false;
updateSelectionRect();
};
Demo: https://codesandbox.io/s/multiple-selection-react-hooks-and-konva-forked-tgggi?file=/src/index.js
Upvotes: 2