Я написал небольшую программу, в которой я пытаюсь сделать движущийся "пузырьковый" фон.Для этого я использую холст HTML.Я попытался представить каждый пузырь с помощью объекта JavaScript.Когда я перебираю список, я получаю сообщение об ошибке.Ошибка:
Uncaught TypeError: Cannot read property 'color' of undefined
at drowBouble (app.js:44)
at drowBoubles (app.js:38)
at generateBoubles (app.js:29)
at app.js:57
drowBouble @ app.js:44
drowBoubles @ app.js:38
generateBoubles @ app.js:29
(anonymous) @ app.js:57
Я попытался console.log () индексировать в функции drowBouble (), и на последней итерации результат был неопределенным.Зачем?Как я могу это исправить?
Мой app.js:
var canvas = document.getElementById("cv");
let width = window.innerWidth * 0.98;
let height = window.innerHeight * 0.97;
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var boubles = [];
var createBouble = function() {
let x = Math.floor( width * Math.random());
let y = Math.floor(height * Math.random());
let color = getColor();
let radius = 30 + Math.floor(Math.random() * 50);
let xAcc = 10;
let yAcc = 10;
return {x, y, color, radius, xAcc, yAcc};
}
var getColor = function() {
return 'rgba(' + Math.floor(Math.random() * 255) + ', ' + Math.floor(Math.random() * 255) + ', ' + Math.floor(Math.random() * 255) + ', ' + 0.3 + ')';
}
var generateBoubles = function(amount) {
for (let i = 0; i < amount; i++) {
boubles.push(createBouble());
}
drowBoubles();
}
var drowBoubles = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < boubles.length; i++) {
drowBouble(i);
updateBouble(i);
}
setTimeout(drowBouble(), 100);
}
var drowBouble = function(index) {
console.log(index);
console.log(boubles.length);
context.fillStyle = boubles[index].color;
context.beginPath();
context.arc(boubles[index].x, boubles[index].y, boubles[index].radius, 0, 2 * Math.PI);
context.fill();
}
var updateBouble = function(index){
let bouble = boubles[index];
bouble.x += bouble.xAcc;
bouble.y += bouble.yAcc;
boubles[index] = bouble;
}
generateBoubles(20);