如何在KineticJS中获取相对于其图层的点击事件的位置? [英] How to get the position of a click event relative to its layer in KineticJS?

查看:80
本文介绍了如何在KineticJS中获取相对于其图层的点击事件的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用HTML5开发一个十六进制网格策略游戏,因为向UI添加更多按钮变得很复杂,我正在用KineticJS重写我的代码来绘制画布。

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....);
    }
})

基本上我想要的是相对于CANVAS的点击事件的位置。从现在开始KineticJS控制画布,并且它不允许我设置画布ID,我不能再使用 getElementById 来选择我的画布。有没有其他方法可以做到这一点?

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?

可能有一些方法我没想到可以设置画布ID,但我期待更优雅的解决方案,理想情况下通过KineticJS API。

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.

谢谢。

推荐答案

我发现了最好的方法是......

I found out the best way to do it is...

var bgxy = bg.getAbsolutePosition();
var x = event.pageX - stage.getContainer().offsetLeft - bgxy.x;
var y = event.pageY - stage.getContainer().offsetTop - bgxy.y;

这篇关于如何在KineticJS中获取相对于其图层的点击事件的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆