Nevin Madhukar K Nevin Madhukar K - 1 year ago 102
jQuery Question

Kineticjs output lags

I am trying to recreate the sinuous game.(
I created the red enemies,but it lags(slows down) after some time.

My code is given below:
Javascript as follows:

var x = 0;
var y = 0;
var noOfEnemies = 10;
var enemyArmada = new Array();

var stage = new Kinetic.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
listening: true
var layer = new Kinetic.Layer({
listening: true


function createEnemy() {
for (var i = 0; i < noOfEnemies; i++) {
var enemy = new Kinetic.Circle({
x: Math.random() * 1200,
y: Math.random() * 50,
radius: 6,
fill: 'red',
stroke: 'black',
speed: 3 + Math.random() * 5

setInterval(draw, 60);

function draw() {
for (var i = 0; i < noOfEnemies; i++)
x: enemyArmada[i].getPosition().x + 5,
y: enemyArmada[i].getPosition().y + 5


<!DOCTYPE html>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../css/style.css"/>
<!--<canvas id="canvasRegn" width="600" height="450" style="margin:100px;"></canvas>-->
<div id="container" style="width: auto; height: auto; background:#000; margin:auto; float:left;"></div>
<script src="../js/jquery.min.js"></script>
<script src="../js/kinetic-v5.0.0.min.js"></script>
<script type="text/javascript" src="../js/rain2.js"></script>


Answer Source

I suggest using Kinetic.Animation class instead of setInterval.

They move slower since their is speed is in px/s now.

All you do is start the animation (anim.start();), and update the positions:

var anim = new Kinetic.Animation(function(frame) {
        for (var i = 0; i < noOfEnemies; i++) {
        var e=enemyArmada[i];
            x: e.position().x + e.speedX * frame.timeDiff / 1000,
            y: e.position().y + e.speedY * frame.timeDiff / 1000
      }, layer);

Where frame timeDiff is the time difference between two consecutive frames, measured in ms. Learning to use animations will help you in the long run, since you can time what is happening pretty exactly (frame.time, frame.timeDiff).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download