试试下面的代码,你可以在圆圈上通过鼠标移动找到圆圈ID
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid #9C9898;
}
</style>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.1.js"></script>
<script>
window.onload = function() {
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var circlesLayer = new Kinetic.Layer();
var tooltipLayer = new Kinetic.Layer();
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'cyan', 'purple'];
var colorIndex = 0;
var circleId ;
for(var n = 0; n < 100; n++) {( function() {
var i = n;
var color = colors[colorIndex++];
if(colorIndex >= colors.length) {
colorIndex = 0;
}
circleId = "CircleID_" + i;
var randX = Math.random() * stage.getWidth();
var randY = Math.random() * stage.getHeight();
var circle = new Kinetic.Circle({
x: randX,
y: randY,
radius: 10,
fill: color,draggable:true,
id:circleId
});
circle.on('mousemove', function() {
// update tooltip
var mousePos = stage.getMousePosition();
tooltip.setPosition(mousePos.x + 5, mousePos.y + 5);
tooltip.setText('ID: ' + stage.get("#CircleID_" + i)[0].attrs.id);
tooltip.show();
tooltipLayer.draw();
});
circle.on('mouseout', function() {
tooltip.hide();
tooltipLayer.draw();
});
circlesLayer.add(circle);
}());
}
var tooltip = new Kinetic.Text({
text: '',
fontFamily: 'Calibri',
fontSize: 12,
padding: 5,
visible: false,
fill: 'black',
opacity: 0.75,
textFill: 'white'
});
tooltipLayer.add(tooltip);
stage.add(circlesLayer);
stage.add(tooltipLayer);
};
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>