¿Por qué solo estoy obteniendo un rectángulo?
En este código, espero obtener una salida con 5 rectángulos que giran alrededor del punto central de la ventana en diferentes radios como los planetas que giran alrededor del Sol en el sistema solar.
Pero solo obtengo un rectángulo y ni siquiera está girando.
Estoy atrapado y no entiendo por qué no está funcionando.
let canvas, ctx, W, H;
canvas = document.createElement(‘canvas’);
document.body.appendChild(canvas);
ctx = canvas.getContext(‘2d’);
let objArr = [];
const init = () => {
canvas.width = W = innerWidth;
canvas.height = H = innerHeight;
canvas.style.background = ‘#dedfda’;
for (let i = 0; i <= 5; i++) {
let r = (i + 1) * 20;
objArr.push(new Rectangle(W / 2, H / 2, 10, 10, “red”, innerWidth / 2, innerHeight / 2, r));
objArr[0].draw();
}
animate();
}
const random = (min = 0, max = 1) => Math.random() * (max – min) + min;
class Rectangle {
constructor(posX, posY, w, h, color, cx, cy, r) {
this.posX = posX;
this.posY = posY;
this.w = w;
this.h = h;
this.color = color;
this.cx = cx;
this.cy = cy;
this.r = r;
this.angle = 0;
}
draw() {
ctx.clearRect(0, 0, innerWidth, innerHeight);
ctx.fillStyle = this.color;
ctx.fillRect(this.posX, this.posY, this.w, this.h);
}
update() {
this.angle += 0.1;
this.posX = this.cx + this.r * Math.cos(this.angle);
this.posY = this.cy + this.r * Math.sin(this.angle);
this.draw();
}
}
const animate = () => {
objArr.forEach(e => {
e.update();
})
requestAnimationFrame(animate);
}
window.onload = init;
davy.ai
Hay algunas posibles razones por las que no estás viendo la salida esperada:
draw()
del primer objeto en el array. Sin embargo, los rectángulos siguientes no se están dibujando en absoluto. Para solucionar esto, puedes llamar al métododraw()
de cada objeto Rectangle dentro del bucle, así:update()
de la clase Rectangle, la posición del rectángulo se actualiza en función de su ángulo y radio, pero el ángulo no se está incrementando correctamente. Para solucionar esto, puedes agregar una variable que controle la velocidad de la revolución e incrementar el ángulo por esa cantidad en cada fotograma. Por ejemplo:Con estos cambios, el código debería funcionar como se espera y mostrar varios rectángulos girando alrededor del punto central con diferentes radios.