Kinetic在点击时获得特定的形状ID

时间:2012-12-03 16:12:45

标签: javascript mouse kineticjs

我只是想为每个形状设置一个点击事件,我希望能够向我显示它所基于ID的方格。

var stage = new Kinetic.Stage({
container: 'container',
    width: 700,
    height: 700,
});


var squareLayer;
var boardBlankArray;

function drawBoard() {
    var squareLayer = new Kinetic.Layer();
    var initialSquares = 64;
    var squareX = 20;
    var squareY = 20;
    boardBlankArray = [];

for (i = 0; i < initialSquares; i++) {
    var square = new Kinetic.Rect({
        x: squareX,
        y: squareY,
        width: 50,
        height: 50,
        fill: "blue",
        stroke: "black",
        strokeWidth: 2,
        id: "squares" + i
    });

    squareX += 60; //update squares X (horizontal) position
    if (squareX > 450) {
        squareX = 20;
        squareY += 60;
    }


    boardBlankArray[i] = square;

    squareLayer.add(boardBlankArray[i]);

    boardBlankArray[i].on("click", function() {
        alert(boardBlankArray[i].getId());
    });
}
  stage.add(squareLayer);
}


drawBoard();

http://jsfiddle.net/tSvmd/

我做了小提琴,由于某种原因,它说boardBlankArray是未定义但显然是。此外,当我在我的计算机上本地执行此操作时,我没有收到该错误。相反,它只是警告所有方块的相同ID。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

尝试使用 this.attrs.id 代替 boardBlankArray [i] .getId()作为形状ID


固定输出:

http://jsfiddle.net/tSvmd/1/

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type='text/javascript' src='http://www.kineticjs.com/download/v4.0.5/kinetic-v4.0.5.min.js'></script>
<script type='text/javascript'>
window.onload=function(){
var stage = new Kinetic.Stage({
    container: 'container',
    width: 700,
    height: 700,
});
var squareLayer;
var boardBlankArray;
function drawBoard() {
    var squareLayer = new Kinetic.Layer();
    var initialSquares = 64;
    var squareX = 20;
    var squareY = 20;
    boardBlankArray = [];
    for (i = 0; i < initialSquares; i++) {
        var square = new Kinetic.Rect({
            x: squareX,
            y: squareY,
            width: 50,
            height: 50,
            fill: "blue",
            stroke: "black",
            strokeWidth: 2,
            id: "squares" + i
        });
        squareX += 60; //update squares X (horizontal) position
        if (squareX > 450) {
            squareX = 20;
            squareY += 60;
        }
        boardBlankArray[i] = square;
        squareLayer.add(boardBlankArray[i]);
        boardBlankArray[i].on("click", function() {
            alert(this.attrs.id);
        });
    }
     stage.add(squareLayer);
}
drawBoard();
}
</script>
</head>
<body>
<div id="container">
</div>
</body>
</html>

答案 1 :(得分:1)

尝试使用此代替点击,使用evt.shape获取事件的形状对象并在该对象上使用getId()

   boardBlankArray[i].on("click", function(evt) {
var node=evt.shape;
            alert(node.getId());
        });