According to my Prof, I need to make the dots in dotArray to move randomly. I created a draw function that allocated the xpos and ypos of the dots in dotArray according to xrate and yrate. But when I load the html page, the console window shows an error message that says "Cannot read property 'xpos' of undefined". And the dots do not move. Can anyone tell me what is wrong with this code?
var randInt = function (lim){
return Math.floor(lim*Math.random());
};
// Generate random hsl color
var color = "hsl("+[0,0,0].map(function(){
return Math.round(100*Math.random())+"%"; }).join(',')+")";
// Qn1. Create array of dots
var dotArray = [1,100]
var i = 0; //initialize array
// Qn3 Create map function
var x = randInt(2) // x is a random number between 0 & 1
var map = function(x,a,b,n,m){
// String to link x,a,b,n,m
return n + (m-n)*(x-a)/(b-a);
};
// Creates 100 dots
while (i < 100){
dotArray[i] = paper.circle(randInt(pWidth), randInt(pWidth), 20)
dotArray[i].attr({
"fill": color, // Qn5 Initialize color to a random hue
"opacity": 0.5,// Qn6 Made the dots semi-transparent by changing its opacity attribute
});
// Initialize position of dots
dotArray[i].xpos = randInt(pWidth);
dotArray[i].ypos = randInt(pHeight);
// Initialize rate
dotArray[i].xrate = 5;
dotArray[i].yrate = 5;
// Draw function to change xpos and ypos of dots according to xrate and yrate.
var draw = function(){
dotArray[i].xpos += dotArray[i].xrate;
dotArray[i].ypos += dotArray[i].yrate;
dotArray[i].attr({'cx': dotArray[i].xpos, 'cy': dotArray[i].ypos});
if (dotArray[i].xpos > pWidth) {dotArray[i].xrate = -dotArray[i].xrate;}
if (dotArray[i].ypos > pHeight) {dotArray[i].yrate = - dotArray[i].yrate};
if (dotArray[i].xpos < 0) {dotArray[i].xrate = -dotArray[i].xrate;}
if (dotArray[i].ypos < 0) (dotArray[i].yrate = - dotArray[i].yrate);
};
console.log("dotArray is " + dotArray[i]); // Console msg to keep track of dots in the array
i++; // Increment of i at end of loop.
};
// Calls draw function
setInterval(draw, 20);
Aucun commentaire:
Enregistrer un commentaire