gpt4 book ai didi

javascript - Kinetic 在点击时获取特定的形状 ID

转载 作者:行者123 更新时间:2023-11-30 13:11:37 24 4
gpt4 key购买 nike

我只是想为每个形状设置一个点击事件,我希望能够根据它们的 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/

我制作了 fiddle ,出于某种原因,它说 boardBlankArray 未定义,但显然是。此外,当我在我的计算机上本地执行此操作时,我不会收到该错误。相反,它只是提醒所有方 block 的相同 ID。

如有任何帮助,我们将不胜感激。

最佳答案

尝试使用 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>

关于javascript - Kinetic 在点击时获取特定的形状 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13687259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com