我有一些HTML,可以在画布周围弹起球,但当我将坐标设置为随机位置并使用alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));测试时,存储坐标的数组似乎是“alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));”。这将返回“协调NaN x NaN”。我试着用一个没有阵列的球来做这件事,它成功了。我不确定我是对数组进行了糟糕的编码,还是它是其他的东西。以下是我的HTML:
<!Doctype HTML>
<head>
<script>
var cirX = [];
var cirY = [];
var chX = [];
var chY = [];
var width;
var height;
function initCircle(nBalls) {
alert(nBalls)
for(var i = 0; i<nBalls;i++) {
alert("loop " + i)
chX[i] = (Math.floor(Math.random()*200)/10);
chY[i] = (Math.floor(Math.random()*200)/10);
cirX[i] = Math.floor(Math.random()*width);
cirY[i] = Math.floor(Math.random()*height);
alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));
circle(cirX[i],cirY[i],3);
setInterval('moveBall(i)',10);
}
}
function moveBall(ballNum) {
if(cirX[ballNum] > width||cirX[ballNum] < 0) {
chX[ballNum] = 0-chX[ballNum];
}
if(cirY[ballNum] > height|| cirY[ballNum] < 0) {
chY[ballNum] = 0-chY[ballNum];
}
cirX[ballNum] = cirX[ballNum] + chX[ballNum];
cirY[ballNum] = cirY[ballNum] + chY[ballNum];
circle(cirX[ballNum],cirY[ballNum],3);
}
function circle(x,y,r) {
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
canvas.width = canvas.width;
ctx.fillStyle="#FF0000";
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, true);
ctx.fill();
width = canvas.width;
height = canvas.height;
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300">
</canvas>
<script>
initCircle(3); //this sets the number of circles
</script>
</body>我已经查过如何初始化数组e.c.t,但我似乎做得对吗?提前感谢您的帮助!
编辑:
尽管解决了上述问题,但在moveBall()中,尽管moveBall()中的变量为0到2(通过添加alert(ballNum)进行测试),但仍只有一个球在不同的移动速度和不同的速度。有人知道为什么吗?
发布于 2013-03-05 19:54:27
你打电话给这条线
cirX[i] = Math.floor(Math.random()*width);当width仍未定义时。因此,结果只能得到NaN。
要正确地从moveBall调用setInterval函数,可以使用
(function(i) { // embedds i to protect its value (so that it isn't the one of end of loop
setInterval(function(){moveBall(i)}, 10);
})(i);发布于 2013-03-05 20:00:26
这是因为当第一次执行语句时,width是未定义的。您可以在开始时获得画布及其维度,并将其保持为全局。
http://jsbin.com/agavoq/9/edit
要调用setInterval,可以使用保持i值的自调用函数
(function(x){
setInterval(moveBall,10, x);
})(i);或者简单的
setInterval(moveBall,10, i);或
setInterval('moveBall(' + i+ ')',10);发布于 2013-03-05 19:53:04
我看到了另一个问题,因为看看这一行
setInterval('moveBall(i)',10);i不是你想象的那样。您不应该在setTimeout中使用字符串。
https://stackoverflow.com/questions/15232812
复制相似问题