JSFiddle - React, Tailwind, and code Playground
by Simonwep
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@simonwep/selection-js/dist/selection.min.js"></script>
<meta charset="utf-8" />
<title>Konva Groups Demo</title>
</head>
<body>
<div class="example" id="container"></div>
</body>
</html>
CSS
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
.selection-area {
background: rgba(0, 0, 255, 0.1);
border-radius: 0.1em;
border: 0.05em solid rgba(0, 0, 255, 0.2);
}
JavaScript
const width = window.innerWidth;
const height = window.innerHeight;
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
const layer = new Konva.Layer();
const group = new Konva.Group({
x: 120,
y: 40,
rotation: 20
});
const colors = ['red', 'orange', 'yellow'];
const box = new Konva.Rect({
x: 0 * 30,
y: 0 * 18,
width: 100,
height: 50,
name: colors[0],
fill: colors[0],
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(box);
const box1 = new Konva.Rect({
x: 1 * 30,
y: 1 * 18,
width: 100,
height: 50,
name: colors[1],
fill: colors[1],
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(box1);
const box2 = new Konva.Rect({
x: 2 * 30,
y: 2 * 18,
width: 100,
height: 50,
name: colors[2],
fill: colors[2],
stroke: 'black',
strokeWidth: 4,
draggable: true
});
layer.add(box2);
stage.add(layer);
const selection = Selection.create({
containers: ['.example'],
selectables: ['.example'],
boundarys: ['.example']
}).on('beforestart', () => {
}).on('start', ({
inst,
selected,
oe
}) => {
// Remove class if the user isn't pressing the control key or ⌘ key
if (!oe.ctrlKey && !oe.metaKey) {
// Unselect all elements
for (const el of selected) {
el.classList.remove('selected');
inst.removeFromSelection(el);
}
// Clear previous selection
inst.clearSelection();
}
}).on('move', ({
changed: {
removed,
added
}
}) => {
// Add a custom class to the elements that where selected.
for (const el of added) {
el.classList.add('selected');
}
// Remove the class from elements that where removed
// since the last selection
for (const el of removed) {
el.classList.remove('selected');
}
}).on('stop', ({
inst
}) => {
inst.keepSelection();
const selectedItems = selection.getSelection();
console.log("Selected items array: ", selectedItems);
});