You can use mouseenter
and mouseleave
events to show/hide anchors for the shape.
It is up to you to choose how to implement anchors. It can be custom anchors like in https://konvajs.org/docs/sandbox/Modify_Curves_with_Anchor_Points.htm or it can be Konva.Transformer
https://konvajs.org/docs/select_and_transform/Basic_demo.html.
On mouseenter
you can show anchors. Hiding anchors is a bit tricker for the demo I will hide anchors when mouse is too far away from the shape. We can't use mouseleave
as is here, because it will trigger hide when we simply hover Konva.Transformer
.
In the demo, try to hover the circle.
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
const shape = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 50,
fill: 'green'
});
layer.add(shape);
const tr = new Konva.Transformer();
layer.add(tr);
// from https://stackoverflow.com/questions/5254838/calculating-distance-between-a-point-and-a-rectangular-box-nearest-point
function getDistance(rect, p) {
var dx = Math.max(rect.x - p.x, 0, p.x - (rect.x + rect.width));
var dy = Math.max(rect.y - p.y, 0, p.y - (rect.y + rect.height));
return Math.sqrt(dx*dx + dy*dy);
}
shape.on('mouseenter', () => {
tr.nodes([shape]);
});
stage.on('mousemove', () => {
if (!tr.nodes().length) {
return;
}
if (tr.isTransforming()) {
return;
}
const rect = shape.getClientRect();
const dist = getDistance(rect, stage.getPointerPosition());
if (dist > 60) {
tr.nodes([]);
}
});
layer.draw();
<script src="https://unpkg.com/konva@^8/konva.min.js"></script>
<div id="container"></div>