为什么不通过 KineticJS 处理鼠标事件呢?
layer.on('click', function(evt) {
// get the shape that was clicked on
var shape = evt.targetNode;
alert('you clicked on \"' + shape.getName() + '\"');
});
事件委托:http ://www.html5canvastutorials.com/kineticjs/html5-canvas-get-event-shape-with-kineticjs/
事件:http ://www.html5canvastutorials.com/kineticjs/html5-canvas-path-mouseover/
更新:
我误解了你的问题,所以我很抱歉。
您希望targetNode
在按下键时访问(keydown 事件)。这是我的做法:
首先你需要设置一个透明的矩形背景和舞台的宽度和高度,以便图层可以检测到鼠标事件(在这种情况下我们需要mousemove
)。
var bg = new Kinetic.Rect({
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight(),
id: 'bg'
});
Kinetic.Shape
然后,每当鼠标在舞台内移动但不在目标上时,我都会设置一个空。因此,除非鼠标悬停在透明背景以外的节点上,否则target
始终等于。只需在舞台上打印您的分数。empty
scoreText
var empty = new Kinetic.Shape({
id: 'empty'
});
var target = empty;
var score = 0;
var scoreText = new Kinetic.Text({
text: 'Score: '+score,
x: 10,
y: 10,
fill: '#000',
fontSize: 20,
id: 'score'
});
mousemove
在 KineticJS 中使用事件:
layer.on('mousemove', function (e) {
var mousePos = stage.getMousePosition();
var x = mousePos.x;
var y = mousePos.y;
var node = e.targetNode;
var nodeID = node.getId();
if (nodeID !== 'bg') {
target = node;
} else {
target = empty;
}
});
然后使用 jQuerykeydown
事件:
$(document).keydown(function(e) {
if (e.keyCode == 90) {
var id = target.getId();
if (id == 'empty' || id == 'score') {
alert('MISS');
} else {
var targetID = target.getId();
var targetName = target.getName();
alert('ID: ' + targetID + ' NAME: ' + targetName + ' You get one point!');
target.destroy();
target = empty;
score++;
updateScore(scoreText, score);
randomCircle();
}
}
});
最后,为了制作游戏.. randomCircle()
andupdateScore()
函数:
function updateScore(text, score) {
text.setText('Score: ' + score);
//layer.draw(); //normally we would have to layer.draw() here, but I called it in randomCircle() instead to save the amount of draw() calls necessary
}
function randomCircle() {
var circle = new Kinetic.Circle({
x: Math.floor((Math.random() * 578)),
y: Math.floor((Math.random() * 200)),
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
id: 'someTarget',
name: 'targets'
});
layer.add(circle);
layer.draw();
}
jsfiddle(不要忘记单击 javascript 窗格才能使用 keydown 事件!)