Question

I can't figure out why the co-ordinates for the canvas lines aren't being digested using the arrays: any suggestions?

I'm trying to create an algorithm for randomly generated sets of lines which eventually link together from where the last one ended. like a snake that gets longer if you like.

     var c = document.getElementById("playground");
     var ctx = c.getContext("2d"); 

  //global scope
  var i; 
var c1 = []; //c is short for collect
var c2 = [];
var c3 = [];
var c4 = [];

var initiate = function(){ //the buttom that triggers the program


var clock = function(){

 /* if(i){  
 alert(i); 
}*/

  i+=1; //increment each time the..
  //function gets called. 

 var a = Math.round(Math.random()*200); 
 var b = Math.round(Math.random()*200); 
 var c = Math.round(Math.random()*200); 
 var d = Math.round(Math.random()*200); 
 c1.push(a); 
 c2.push(b);
 c3.push(c);
 c4.push(d);


   ctx.beginPath(); 
   ctx.moveTo(c1[i], c2[i]);  //Here is where the issue seems to be? they don't run.
   ctx.lineTo(c3[i], c4[i]); 
   ctx.stroke(); 

    //if(c1.length===10){
    //alert(c1);
    //}

   }; //end of clock

    setInterval(clock,80);



    }; //end of parent function
Was it helpful?

Solution

You are initializing i as var i;. When you increment it, it results in NaN, so just initialize it as var i = 0; or the like instead.

EDIT: Also why your problem is at that line is because you are trying to access the NaNth element of an array, which JavaScript doesn't like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top