Reference not found for object property

3

I developed a simple particle code in codepen.io and in its execution it generates a log with the error:

Uncaught TypeError: Cannot read property 'color' of undefined

What is the reason for the error?

// inicia o canvas
var canvas = document.getElementById("canvas"),
    W = canvas.width = window.innerWidth,
    H = canvas.height = window.innerHeight,
    ctx = canvas.getContext("2d");

function rI(min, max, mode){
  if (mode = 'int'){
    return Math.floor(Math.random() * (max-min) + min);
  }else{
    return Math.random() * (max-min) + min;
  }
}

function genSpeed(min, max, excludeMin, excludeMax){
	var speed;
	do{
    speed = Math.random() * (max - min) + min;
  }while(speed > excludeMin && speed < excludeMax)
  return speed;
}

function createDot(){
  //engine
  this.posX = rI(0, W+1);
  this.posY = rI(0, H+1);
  this.speX = rI(-5, 5,-2,2);
  this.speY = rI(-5, 5,-2,2);
//   this.speX = genSpeed(-5, 5, -1, 1);
//   this.speY = genSpeed(-5, 5, -1, 1);
  
  //style
  this.size = rI(5, 30);
  this.color = 'rgb('+rI(0,256)+','+rI(0,256)+','+rI(0,256)+')';
}

var dots = [];
for(var i = 0; i <= 15; i++){
    dots.push(new createDot());
}

function run(){
  ctx.fillStyle = 'rgb(255,255,255)';
  ctx.fillRect(0, 0, W, H);
  for(var j = 0; j <= dots.length; j++){
    
    
    var d = dots[j];

    ctx.beginPath();
    ctx.fillStyle = d.color; //**O erro no console aponta pra cá**
    ctx.arc(d.posX, d.posY, d.size, Math.PI*2, false);
    ctx.fill();
    
    d.posX += d.speX;
    d.posY += d.speY;
    
    if (d.posX < W + d.size && d.posX > W) d.speX *= -1;
    if (d.posX < 0 - d.size && d.posX < 0) d.speX *= -1;
    if (d.posY < H + d.size && d.posY > H) d.speY *= -1;
    if (d.posY < 0 - d.size && d.posY < 0) d.speY *= -1;
    
  }
}

setInterval(run, 1);

// alert(dots.posX.toString());
body{
  overflow:hidden;
}
<canvas id="canvas"></canvas>

Here's the pen Particles

    
asked by anonymous 16.01.2015 / 14:22

1 answer

4

In run , you are moving to a position where the point set is unregistered.

for(var j = 0; j <= dots.length; j++){ <- errado
for(var j = 0; j < dots.length; j++){  <- correto

See the for test.

Link to pen

    
16.01.2015 / 14:58