I'm trying to create an effect where clouds float across the screen. I tried wrapping the entire process of creating the cloud shape and cloud group inside of a function, putting the animation in the function, and then putting that function inside of a setInterval. It works in the sense that the animation repeats, except it steadily builds speed and starts going insanely fast.
Does anybody know what's going on here? I used this same strategy in another part of my program and it worked well. The only difference is that I was creating one shape rather than three shapes and a group inside that function.
Please let me know, thanks!
var cloudy = function(){
var bigCloud = new Kinetic.Group({});
var cloud1 = new Kinetic.Circle({
x:257,
y:28,
radius:8,
fill:'white'
})
var cloud2 = new Kinetic.Circle({
x:283,
y:28,
radius:8,
fill:'white'
})
var cloud3 = new Kinetic.Circle({
x:270,
y:26,
radius:13,
fill:'white'
})
bigCloud.add(cloud1);
bigCloud.add(cloud2);
bigCloud.add(cloud3);
skyLayer.add(bigCloud);
cloudx=500;
var cloudMove = new Kinetic.Animation(function(){
bigCloud.setX(cloudx);
cloudx-=2;
},skyLayer);
cloudMove.start();
};
setInterval(function(){
cloudy();
},1000)
You're creating a new animation with every call to cloudy.
Every new and existing animation is moving bigCloud by -2.
Here's an example that uses 1 animation to animate and also to create new clouds.
Demo: http://jsfiddle.net/m1erickson/jG3BL/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
function addCloud(){
var circle1 = new Kinetic.Circle({
x:30,
y:30,
radius: 10,
fill: randomColor(),
});
layer.add(circle1);
layer.draw();
}
var newCloudCountdown=120;
var cloudMove=new Kinetic.Animation(function(){
var clouds=layer.getChildren();
clouds.each(function(child){
child.x(child.x()+.25);
});
if(--newCloudCountdown<0){
addCloud();
newCloudCountdown=120;
}
},layer);
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
// Go
addCloud();
cloudMove.start();
}); // end $(function(){});
</script>
</head>
<body>
<button id="myButton">Button</button>
<div id="container"></div>
</body>
</html>