如何删除 html canvas 中不需要的行?

How to delete unwanted lines in html canvas?

我想知道如何删除我的 cercles 之间创建的线。 在学校,我们应该在 html 页面中创建布朗运动,其中 canvas 成组,而我应该负责绘制 canvas 和分子。 所以我编写了以下代码,其中我创建了一个 ctx.arc 来制作一个圆圈,我为 400 个分子放置了随机坐标,但在每个圆圈之间绘制了一条线,因此它使我的 canvas 看起来像艺术品... 我们从 html 开始,我们的老师说我们必须在 Internet 上搜索才能找到一些解决方案,但我找不到关于这个主题的任何内容。

所以我的代码是:

<!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)

因此,如果有人可以帮助我解决这个不需要的行的问题,我将不胜感激:)

祝你白天/晚上愉快。

在您的 while 循环中,您必须调用函数 "beginPath"。

形成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>