我有一个点数组(x,y对),我用这些点绘制圆圈
for (var i = 0; i < points.length;i++){
var circle = new Kinetic.Circle({
x: points[i].x,
y: points[i].y,
radius: 7,
fill: "green",
stroke: "black",
name:i,
strokeWidth: 2
});
circle.on("click", function() {
alert(name); //here I want to get name of circle
});
layer.add(circle);
}
我为每个圈子添加了新的属性名称,比如ID,我想在点击鼠标时提醒圈子的名称。
我不确定向圈子添加新的属性名称是否正确。
那么,如何将新属性“name”添加到圈子中,以便在点击圈子时提醒其名称值?
答案 0 :(得分:2)
请尝试以下代码
<!DOCTYPE HTML>
<html>
<head>
<style>
body
{
margin: 0px;
padding: 0px;
}
</style>
</head>
<body onload="displaycircle()">
<div id="container">
</div>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.0.js"></script>
<script>
function displaycircle() {
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
for (var i = 0; i < 10; i++) {
var circle = new Kinetic.Circle({
x: Math.random() * stage.getWidth(),
y: Math.random() * stage.getHeight(),
radius: 30,
fill: "green",
stroke: "black",
name: i,
strokeWidth: 2,
draggable: true
});
layer.add(circle);
stage.add(layer);
circle.on("click", function() {
alert(this.attrs.name); //here you can get name of circle
});
}
}
</script>
</body>
</html>