node.getRelativePointerPosition() method

This commit is contained in:
Anton Lavrenov 2021-05-08 21:43:51 -05:00
parent f8e71d608a
commit 3219008dfa
4 changed files with 57 additions and 2 deletions

View File

@ -25,6 +25,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
- Full event system rewrite. Much better `pointer` evens support.
- `Konva.Util.extend` is removed
- Added `Konva.Util.degToRad` and `Konva.Util.radToDeg`
- Added `node.getRelativePointerPosition()`
## 7.2.5

View File

@ -1120,6 +1120,33 @@ export abstract class Node<Config extends NodeConfig = NodeConfig> {
y: this.y(),
};
}
/**
* get position of first pointer (like mouse or first touch) relative to local coordinates of current node
* @method
* @name Konva.Node#getRelativePointerPosition
* @returns {Konva.Node}
* @example
*
* // let's think we have a rectangle at position x = 10, y = 10
* // now we clicked at x = 15, y = 15 of the stage
* // if you want to know position of the click, related to the rectangle you can use
* rect.getRelativePointerPosition();
*/
getRelativePointerPosition() {
if (!this.getStage()) {
return null;
}
// get pointer (say mouse or touch) position
var pos = this.getStage().getPointerPosition();
if (!pos) {
return null;
}
var transform = this.getAbsoluteTransform().copy();
// to detect relative position we need to invert transform
transform.invert();
// now we can find relative point
return transform.point(pos);
}
/**
* get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor
* @method

View File

@ -282,9 +282,9 @@ export class Stage extends Container<Layer> {
return this;
}
/**
* returns absolute pointer position which can be a touch position or mouse position
* returns ABSOLUTE pointer position which can be a touch position or mouse position
* pointer position doesn't include any transforms (such as scale) of the stage
* it is just a plain position of pointer relative to top-left corner of the stage container
* it is just a plain position of pointer relative to top-left corner of the canvas
* @method
* @name Konva.Stage#getPointerPosition
* @returns {Vector2d|null}

View File

@ -12,6 +12,7 @@ import {
loadImage,
Konva,
isBrowser,
simulateMouseMove,
} from './test-utils';
describe('Node', function () {
@ -3807,4 +3808,30 @@ describe('Node', function () {
stage.x(10);
assert.equal(circle.isClientRectOnScreen(), true);
});
// ======================================================
it('getRelativePointerPosition() method', function () {
var stage = addStage();
var layer = new Konva.Layer({
scaleX: 2,
});
stage.add(layer);
var circle = new Konva.Circle({
x: 100,
y: 100,
radius: 30,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);
simulateMouseMove(stage, {
x: 100,
y: 100,
});
assert.equal(circle.getRelativePointerPosition().x, -50);
assert.equal(circle.getRelativePointerPosition().y, 0);
});
});