【发布时间】:2015-10-20 08:36:04
【问题描述】:
根据我的教授的说法,我需要让 dotArray 中的点随机移动。我创建了一个绘制函数,根据 xrate 和 yrate 分配 dotArray 中点的 xpos 和 ypos。但是当我加载 html 页面时,控制台窗口会显示一条错误消息,上面写着“无法读取未定义的属性 'xpos'”。并且点不动。谁能告诉我这段代码有什么问题?
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);
【问题讨论】:
标签: javascript arrays random raphael