How to find relative mouse position?

In some cases you may need to find position of a point relative to a node. For purpose we can use mathematical Konva.Transform methods.

In this demo we have deep nesting transformed nodes: moved stage, scaled layer, rotated group.
Now we want to add circles into the group on click. But how to find position of that circles?
We can’t use stage.getPointerPosition() directly because that is position relative to top-left corner of the stage.

The idea is simple. We just need to use inverted absolute transform.

Relative Pointer Position Demoview raw
<!DOCTYPE html>
<html>

<head>
<script src="https://unpkg.com/konva@2.4.2/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Relative Pointer Position Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
x: 50,
y: 50
});

var layer = new Konva.Layer({
scaleX: 1.5,
scaleY: 0.8,
rotation: 10
});
stage.add(layer);

var group = new Konva.Group({
x: 50,
rotation: 10,
scaleX: 2
});
layer.add(group);

var text = new Konva.Text({
text: 'Click on the canvas to draw a circle',
});
group.add(text);
layer.draw();


stage.on('click', function () {
// what is transform of parent element?
var transform = group.getParent().getAbsoluteTransform().copy();

// to detect relative position we need to invert transform
transform.invert();

// now we find relative point
var pos = stage.getPointerPosition();

var circlePos = transform.point(pos);

layer.add(new Konva.Circle({
x: circlePos.x,
y: circlePos.y,
fill: 'red',
radius: 20
}))
layer.draw();
})

</script>

</body>

</html>
Next