Search code examples
javascripthtmlcanvaslineautomatic-ref-counting

How to delete unwanted lines in html canvas?


I would like to know how to delete the lines that are created between my cercles. At school we are supposed to create the Brownian Motion in a html page with a canvas in groups and I'm the one supposed to do the drawing of the canvas and of the molecules. So I made the following code where I created a ctx.arc to make a circle and I've put random coordinates for 400 molecules but between each circle, a line is drawed so it makes my canvas look like art... We are beginning in html and our teachers said that we'll have to search on Internet to find some solutions but I can't find anything on this subject.

So my code is :

<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>Canvas
</title>
</head>
<body>
<canvas id="canvas" width="800" height="500" style="border:1px solid #000000;">
Sorry, your browser can't support this canvas
</canvas>
<script>
function draw()
{
  var canvas = document.getElementById("canvas"); 
  var ctx = canvas.getContext("2d");
  let i = 0;
  while (i<400){
    ctx.arc(Math.random()*((796-(5))+5), Math.random()*((496-(5))+5), 4, 0, 2 * Math.PI);
	i++;
	}
  ctx.stroke();
  
}
draw();  
</script>
</body>

My canvas (failed)

So if someone could help me with this problem of unwanted lines I would be grateful :)

Have a good day / night.


Solution

  • Inside your while loop you have to call the function "beginPath".

    Form the mozilla web docs

    beginPath()

    Creates a new path. Once created, future drawing commands are directed into the path and used to build the path up.

    <!DOCTYPE html>
    <head>
    <meta charset="utf-8" />
    <title>Canvas
    </title>
    </head>
    <body>
    <canvas id="canvas" width="800" height="500" style="border:1px solid #000000;">
    Sorry, your browser can't support this canvas
    </canvas>
    <script>
    function draw()
    {
      var canvas = document.getElementById("canvas"); 
      var ctx = canvas.getContext("2d");
      let i = 0;
      
      let radius = 4; // Arc radius
      let startAngle = 0; // Starting point on circle
      let endAngle = 2 * Math.PI; // End point on circle
      let anticlockwise = true; // clockwise or anticlockwise
      
      while (i<400)
      {
        ctx.beginPath(); 
        
        let x = Math.random()*((796-(5))+5); // x coordinate
        let y = Math.random()*((496-(5))+5); // y coordinate
        
        ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise );
    		
        ctx.stroke();
        
        i++;
    	}
      
      
      
    }
    draw();  
    </script>
    </body>