Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
¿Cómo mover 2 objetos, uno en el eje X y el otro en el eje Y en Javascript?

Soy nuevo en javascript y necesito animar 2 cuadrados del mismo tamaño usando javascript, uno se mueve en el eje Y y otro en el eje X. cuando ejecuto el código, ambos van en diagonal, ¿qué debo cambiar?

He intentado:

  • cree una función diferente de draw() para el rectángulo azul, lo que resultó en el mismo problema
  • haga una función drawBlueRectangle() que dibuje el rectángulo azul. nada ha cambiado.

el código de los dos rectángulos funciona bien por separado

 var ctx = canvasObject.getContext("2d"); var squareX = 200; var squareY = 150; var diffY = 5; var diffX = 5; var squareSize = 10; var WIDTH = 400; var HEIGHT = 300; function drawRect() { ctx.fillRect(0, 0, WIDTH, HEIGHT); } function drawSquare() { ctx.beginPath(); ctx.fillRect(squareX, squareY, squareSize, squareSize); } function draw() { ctx.fillStyle = "white"; drawRect(); ctx.fillStyle = "red"; drawSquare(); if ((squareY + squareSize) >= HEIGHT) diffY = -diffY; if (squareY <= 0) diffY = -diffY; squareY = squareY + diffY; ctx.fillStyle = "blue"; drawSquare(); if ((squareX + squareSize) == WIDTH) diffX = -diffX; if (squareX <= 0) diffX = -diffX; squareX = squareX + diffX; } setInterval(draw, 30);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Solo un pequeño cambio, mantenga las coordenadas x e y separadas para ambos rectángulos para que la coordenada y permanezca constante (para moverse en el eje x) y lo mismo para el otro. Aquí está el código actualizado

 var ctx = canvasObject.getContext("2d"); var squareX = 100; var squareY = 50; var squareX1 = 100; var squareY1 = 50; var diffY = 5; var diffX = 5; var squareSize = 10; var WIDTH = 400; var HEIGHT = 300; function drawRect() { ctx.fillRect(0, 0, WIDTH, HEIGHT); } function drawSquare() { ctx.beginPath(); ctx.fillRect(squareX, squareY, squareSize, squareSize); } function drawSquare1() { ctx.beginPath(); ctx.fillRect(squareX1, squareY1, squareSize, squareSize); } function draw() { ctx.fillStyle = "black"; drawRect(); ctx.fillStyle = "red"; drawSquare(); if ((squareY+squareSize) > HEIGHT-200) diffY = -diffY; if (squareY <= 0) diffY = -diffY; squareY = squareY + diffY; ctx.fillStyle = "blue"; drawSquare1(); if ((squareX1 + squareSize) > WIDTH-200) diffX = -diffX; if (squareX1 < 0) diffX = -diffX; squareX1 = squareX1 + diffX; } setInterval(draw, 30);
about 4 years ago · Juan Pablo Isaza Relatório

0

Si pasa las coordenadas para dibujar el rectángulo en la función drawSquare , entonces se puede usar el mismo código para dibujar cuadrados en diferentes ubicaciones.

 const canvasObject = document.getElementById("cvs"); const ctx = canvasObject.getContext("2d"); const squareSize = 10; const WIDTH = 400; const HEIGHT = 300; let squareX = 200; let squareY = 150; let diffY = 5; let diffX = 5; function drawSquare(x, y) { ctx.fillRect(x, y, squareSize, squareSize); } function draw() { // Draw background ctx.fillStyle = "white"; ctx.fillRect(0, 0, WIDTH, HEIGHT); // Move squares and handle edge collisions squareY = squareY + diffY; squareX = squareX + diffX; if (((squareY + squareSize) >= HEIGHT) || (squareY <= 0)) { diffY = -diffY; } if (((squareX + squareSize) >= WIDTH) || (squareX <= 0)) { diffX = -diffX; } ctx.fillStyle = "red"; drawSquare(WIDTH / 2, squareY); ctx.fillStyle = "blue"; drawSquare(squareX, HEIGHT / 2); } setInterval(draw, 30);
 <canvas id="cvs" width="400" height="300"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda