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

291
Visualizações
how to make a function runs only once?

I wanted to present a fixed number of circles (in this case 10) on the canvas with a moving line from side to side, the circles function fires for every frame the loop function runs so is there a way to stop it from this behavior. I'm not even sure if I'm thinking right by having circles firing once.

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

fetch("http://api.open-notify.org/astros.json")
  .then((res) => res.json())
  .then((data) => {
    var x = 0;
    var s = 1;
    function circles() {
      for (var i = 0; i < data.number; i++) {
        let randW = Math.floor(Math.random() * (290 - 10) + 10);
        let randH = Math.floor(Math.random() * (140 - 10) + 10);
        ctx.beginPath();
        ctx.fillStyle = "red";
        ctx.arc(randW, randH, 5, 0, 2 * Math.PI);
        ctx.fill();
        ctx.beginPath();
      }
    }
    function draw() {
    //   ctx.clearRect(0, 0, canvas.width, canvas.height); // // use with setInterval(draw,10)
      circles();
      ctx.fill();
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, canvas.height);
      x += s;
      ctx.strokeStyle = "white";
      ctx.stroke();
      if (x == canvas.width || x == 0) {
        s = s * -1;
      }
    }
    // setInterval(draw, 10);
    function loop() {
        ctx.clearRect(0,0,canvas.width, canvas.height);
        draw();
        requestAnimationFrame(loop);
    }
    requestAnimationFrame(loop);
  });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Please check the approach with 2 different canvas elements and separate usage of drawing functions:

const canvas = document.querySelector(".canvas-1");
const ctx = canvas.getContext("2d");

const canvas2 = document.querySelector(".canvas-2");
const ctx2 = canvas2.getContext("2d");

// fetch("http://api.open-notify.org/astros.json")
//   .then((res) => res.json())
//   .then((data) => {
const data = JSON.parse('{"message": "success", "people": [{"name": "Mark Vande Hei", "craft": "ISS"}, {"name": "Pyotr Dubrov", "craft": "ISS"}, {"name": "Anton Shkaplerov", "craft": "ISS"}, {"name": "Zhai Zhigang", "craft": "Shenzhou 13"}, {"name": "Wang Yaping", "craft": "Shenzhou 13"}, {"name": "Ye Guangfu", "craft": "Shenzhou 13"}, {"name": "Raja Chari", "craft": "ISS"}, {"name": "Tom Marshburn", "craft": "ISS"}, {"name": "Kayla Barron", "craft": "ISS"}, {"name": "Matthias Maurer", "craft": "ISS"}], "number": 10}');
var x = 0;
var s = 1;

function circles() {
  for (var i = 0; i < data.number; i++) {
    let randW = Math.floor(Math.random() * (290 - 10)  + 10);
    let randH = Math.floor(Math.random() * (140 - 10) + 10);
    ctx.beginPath();
    ctx.fillStyle = "red";
    ctx.arc(randW, randH, 5, 0, 2 * Math.PI);
    ctx.fill();
    ctx.beginPath();
  }
}
function draw() {
  //   ctx.clearRect(0, 0, canvas.width, canvas.height); // // use with setInterval(draw,10)
  // circles();
  ctx2.fill();
  ctx2.beginPath();
  ctx2.moveTo(x, 0);
  ctx2.lineTo(x, canvas.height);
  x += s;
  ctx2.strokeStyle = "white";
  ctx2.stroke();
  if (x == canvas2.width || x == 0) {
    s = s * -1;
  }
}
circles();
function loop() {
  ctx2.clearRect(0,0,canvas.width, canvas.height);
  draw();
  requestAnimationFrame(loop);
}
loop();
canvas {
  height: 500px;
  width: 500px;
  border: solid 1px;
  background: rgba(0, 0, 0, 0.1);
  position: absolute;
}
<canvas class="canvas-1"></canvas>
<canvas class="canvas-2"></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