I'm developing a hex-grid strategy game in HTML5, and since it becomes complicated to add more buttons to UI, I'm rewriting my code using KineticJS to draw the canvas.
In my game, there is a minimap, and a rectangle in it showing the position of player's camera. When the player clicks on the minimap, the center of his camera will be set to the position he clicked. My original code does not use any external library, and it looks like this:
this.on('click', function(event){
var canvas = document.getElementById('gameCanvas');
var x = event.pageX - canvas.offsetLeft;
var y = event.pageY - canvas.offsetTop;
camera.setPos( // calculate new position based on x and y....);
}
})
So basically what I want is the POSITION OF CLICK EVENT RELATIVE TO THE CANVAS. Since now KineticJS takes control of the canvas, and it does not let me set canvas id, I can't use getElementById
to choose my canvas anymore. Is there another way to do it?
There might be some way I did not figure out that can set the canvas id, but I'm expecting a more elegent solution, idealy through KineticJS API.
Thanks.
Good question, and I think what you are looking for is getAbsolutePosition(). The following is useful things to know from my experience.
getPosition()
getParent()
getX()
getY()
getAbsolutePosition()
Few more useful things,
getScale()
Everything is here in document, http://kineticjs.com/docs/symbols/Kinetic.Node.php
This is an old question, but as I can see, the best answer does not take into account the rotation.
So here it is my solution based on Kinetic v5.1.0. who take into account all transformation.
To get the mouse position on the stage (canvas), you can use:
You can get the mouse position inside a shape click the same way:
You should use
event.layerX
andevent.layerY
:I found out the best way to do it is...