简体   繁体   中英

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM