在 mouseup 处理程序中,将所有圆圈填充重置为黑色,然后将选定圆圈的填充设置为红色:
首先,添加name:"circle"
到您创建的每个圈子,以便您以后可以按名称获取它们:
var circle = new Kinetic.Circle({
x: 50+i*50,
y: 50+i*50,
radius: 10,
fill: 'black',
id: i,
name:"circle"
});
然后在你的 mouseup 处理程序中:
- 将每个圆形填充重置为黑色。
将选定圆圈的填充设置为红色。
circle.on('mouseup', function() {
// reset all circle fills to black
resetToBlackOnMouseUp()
// then set this circle's fill to red
this.setFill('red');
layer.draw();
});
此功能会将所有名为“circle”的圆圈的填充重置为黑色。
// reset all circle fills to black
function resetToBlackOnMouseUp(){
// get all elements named "circle"
var circles=stage.get(".circle");
// set their fills to black
circles.each( function(circle){
circle.setFill("black");
});
}
如果您的舞台上只有一组圆圈,那么您有一个替代且更有效的选择。
您可以保存对先前红色圆圈的引用,然后将该填充重置为黑色。
var redCircle;
// add mouseup handler
circle.on('mouseup', function() {
// reset the previous red circle's fill to black
redCircle.setFill("black");
// then set this circle's fill to red
this.setFill('red');
// now this circle becomes the red circle
redCircle=this;
layer.draw();
});
这是代码和小提琴:http: //jsfiddle.net/m1erickson/CyxSj/
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#buttons {
position: absolute;
top: 5px;
left: 10px;
}
#buttons > input {
padding: 10px;
display: block;
margin-top: 5px;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.5.3.min.js"></script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
stage.add(layer);
for(var i =0; i<10; i++){
var circle = new Kinetic.Circle({
x: 50+i*50,
y: 50+i*50,
radius: 10,
fill: 'black',
id: i,
name:"circle"
});
// add mouseup handler
circle.on('mouseup', function() {
// reset all circle fills to black
resetToBlackOnMouseUp()
// then set this circle's fill to red
this.setFill('red');
layer.draw();
});
layer.add(circle);
console.log(i);
}
layer.draw();
// reset all circle fills to black
function resetToBlackOnMouseUp(){
// get all elements named "circle"
var circles=stage.get(".circle");
// set their fills to black
circles.each( function(circle){
circle.setFill("black");
});
}
</script>
</body>
</html>