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

164
Visualizações
Why my for loop is not drawing multiple repeated shapes in the html canvas sketch?
<html>
<body>
    <canvas width = "1200" height = "1200"> </canvas>


    <script>

        let canvas = document.querySelector('canvas');
        let context = canvas.getContext('2d');


        context.fillStyle = '#5bd75b';
        context.fillRect(0, 0, 1200, 1200);

        let radius = 500;
        for (let i = 1; i <= 10; i++)
        {
          if (Math.random() >= 0.5)
          {
            context.fillStyle = 'yellow';
          }
          else
          {
            context.fillStyle = 'red';
          }
          context.arc(600, 600, radius / i, 0, Math.PI * 2);
          context.fill(); 
         }


    </script>
</body>
</html>

I'm trying to draw multiple circles which will get smaller as the loop runs, but all I get is one big circle, can you please find what's wrong with my code or logic? I'm tired of trying things and finding a solution because my loop's format seems to be right.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When using canvas path functions you need to specify when a path begins and when it ends.
If not done so, all context.arc calls will be merged together into one big path which will be filled every time with the last given color.

Heres the solution to your problem:

context.beginPath();
context.arc(600, 600, radius / i, 0, Math.PI * 2);
context.fill();
context.closePath();
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