The code below should iterate through the array "sequence" (which will contain multiple arrays in the future if you were wondering about the double bracket situation), then execute the function "finalMovement" using the data in sequence[i]. For some unknown reason, the value "sequence[i][n]" is undefined, and I am confused as to why this is, and how I can fix it? Does anyone have any ideas?
var delay;
var sequence = [[1000,"#CAC",5,80]];
for (i=0; i<sequence.length; i++) {
if (i == 0) {
delay = 0;
} else {
delay = ((sequence[i-1][0])*6)+3;
}
console.log(sequence[i]);
setTimeout(() => {finalMovement(sequence[i][0], sequence[i][1], sequence[i][2], sequence[i][3]);}, delay);
}
I've included the entire piece of code below, but the only area that should need to be looked at is above:
<!DOCTYPE html>
<html>
<body>
<canvas id="canvasElement" width=1358 height=608 style="background: #ABC; border: black solid 1px;"/>
<script>
const planeElement = document.getElementById("canvasElement");
const plane = planeElement.getContext("2d");
var x1 = (planeElement.width)/2;
var y1 = (planeElement.height)/2;
var particleSize;
var movement;
var delay;
var sequence = [[1000,"#CAC",5,80]];
for (i=0; i<sequence.length; i++) {
if (i == 0) {
delay = 0;
} else {
delay = ((sequence[i-1][0])*6)+3;
}
console.log(sequence[i]);
setTimeout(() => {finalMovement(sequence[i][0], sequence[i][1], sequence[i][2], sequence[i][3]);}, delay);
}
async function finalMovement (iterations, particleColor, particleVelocity, particleSize) {
movement = [];
for (n=0; n<iterations; n++) {
plane.fillStyle = particleColor;
movement.push([Math.floor(Math.random()*4), particleVelocity]);
}
for (i=0; i<(movement.length); i++) {
if ((x1 < -5)||(x1 > (planeElement.width+5))) {
x1 = (planeElement.width)/2;
} else if ((y1 < -5)||(y1 > (planeElement.height+5))) {
y1 = (planeElement.height)/2;
}
move(movement[i][0], movement[i][1], particleSize);
await sleep(1);
}
}
function move (direction, distance, particleSize) {
if (direction == 0) {
for (d=y1; d>(y1-distance); d--) {
circle(x1,d,particleSize);
}
y1-=distance;
} else if (direction == 1) {
for (d=x1; d<(x1+distance); d++) {
circle(d,y1,particleSize);
}
x1+=distance;
} else if (direction == 2) {
for (d=y1; d<(y1+distance); d++) {
circle(x1,d,particleSize);
}
y1+=distance;
} else if (direction == 3) {
for (d=x1; d>(x1-distance); d--) {
circle(d,y1,particleSize);
}
x1-=distance;
}
}
function circle (x1, y1, particleSize) {
//plane.clearRect(0, 0, 500, 500);
plane.beginPath();
plane.arc(x1, y1, particleSize, 0, 2*Math.PI, false);
plane.fill();
}
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
</script>
</body>
</html>