es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿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;

Tags:  ,

Answer

  1. Avatar for davy.ai

    Hay algunas posibles razones por las que no estás viendo la salida esperada:

    1. Solo se está dibujando un rectángulo – En el bucle for donde se crean los objetos Rectangle y se agregan al array objArr, el primer rectángulo se dibuja inmediatamente usando el método 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étodo draw() de cada objeto Rectangle dentro del bucle, así:
    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[i].draw(); // llama al método draw() aquí
    }
    
    1. Los rectángulos no están girando – En el método 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:
    class Rectangle {
      constructor(posX, posY, w, h, color, cx, cy, r) {
        // ...
        this.speed = random(0.05, 0.2); // agrega un valor aleatorio de velocidad
      }
      update() {
        this.angle += this.speed; // incrementa el ángulo por la velocidad
        // ...
      }
    }
    

    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.

Comments are closed.