Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript arrays giving NaN
    primarykey
    data
    text
    <p>I have a bit of HTML that is supposed to bounce ball(s) around the canvas, but the arrays storing the coordinates seem to be 'NaN' when I set them to a random position and test with <code>alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));</code>. This returns 'Co-ordinates NaN x NaN'. I have tried to do it with one ball without the arrays and it worked. I am not sure if I am coding my arrays badly or if it is something else. Here is my HTML:</p> <pre><code>&lt;!Doctype HTML&gt; &lt;head&gt; &lt;script&gt; var cirX = []; var cirY = []; var chX = []; var chY = []; var width; var height; function initCircle(nBalls) { alert(nBalls) for(var i = 0; i&lt;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] &gt; width||cirX[ballNum] &lt; 0) { chX[ballNum] = 0-chX[ballNum]; } if(cirY[ballNum] &gt; height|| cirY[ballNum] &lt; 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; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas id="canvas" width="400" height="300"&gt; &lt;/canvas&gt; &lt;script&gt; initCircle(3); //this sets the number of circles &lt;/script&gt; &lt;/body&gt; </code></pre> <p>I have looked up how to initialise arrays e.c.t, but I seem to be doing it right? Thanks in advance for your help!</p> <p><strong>EDIT:</strong><br> Despite fixing the above problems, only one ball moves and at varying speeds despite the variable <code>ballNum</code> in <code>moveBall()</code> varying from 0 to 2 as expected (tested by adding <code>alert(ballNum)</code>). Does anyone know why?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload