按名称选择形状与KineticJS,我们可以使用get()方法使用。选择器get()方法返回一个数组的节点匹配选择器字符串。返回的数组是一个动力。集合数组,它基本上是一个典型的JavaScript数组和一个特殊的每个()方法。each()方法使我们能够快速遍历该数组中每个节点。
说明:点击“激活矩形”按钮来选择矩形的名字并执行每一个过渡。你可以拖拽的矩形。
<!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>
<div id="buttons">
<input type="button" id="activate" value="Activate rectangles">
</div>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.min.js"></script>
<script defer="defer">
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
for(var n = 0; n < 10; n++) {
var circle = new Kinetic.Circle({
x: Math.random() * stage.getWidth(),
y: Math.random() * stage.getHeight(),
radius: Math.random() * 50 + 25,
fill: 'red',
strokeWidth: 3
});
layer.add(circle);
}
var rect1 = new Kinetic.Rect({
x: 250,
y: 90,
width: 100,
height: 50,
fill: 'green',
strokeWidth: 3,
offset: {
x: 50,
y: 25
},
draggable: true,
name: 'rectangle'
});
var rect2 = new Kinetic.Rect({
x: 400,
y: 90,
width: 100,
height: 50,
fill: 'green',
strokeWidth: 3,
offset: {
x: 50,
y: 25
},
draggable: true,
name: 'rectangle'
});
layer.add(rect1);
layer.add(rect2);
stage.add(layer);
var tweens = [];
document.getElementById('activate').addEventListener('click', function() {
// select shapes by name
var shapes = stage.get('.rectangle');
// if there are currently any active tweens, destroy them
// before creating new ones
for (var n=0; n<tweens.length; n++) {
tweens[n].destroy();
}
// apply transition to all nodes in the array
shapes.each(function(shape) {
tweens.push(new Kinetic.Tween({
node: shape,
duration: 1,
scaleX: Math.random() * 2,
scaleY: Math.random() * 2,
easing: Kinetic.Easings.ElasticEaseOut
}).play());
});
}, false);
</script>
</body>
</html>