Reference not found for object property

Asked

Viewed 65 times

3

I developed a simple code of particles in codepen.io and its execution 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 is the flash drive Particulas

  • 2

    Post the code here, giving clear indications of where the error is.

  • I updated the post bigown

1 answer

4


In function run, you are traversing to a position that the set of points has no record of.

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

See the test of for.

Link to thumb drive

  • Really, thank you

  • But now I wonder why only the property Colors was not found, being that others were used...

  • The javascript console report is not 100% accurate. If I commented on the Colors property line, it would complain about something else.

  • Mmm got it, thanks man :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.