如何在画布上绘制多个圆圈?

时间:2021-01-10 17:23:54

标签: javascript canvas

我试图在画布中创建多个圆圈,但我的代码一直只创建一个圆圈。我想我做的一切都是正确的,我检查了几个网站如何做到这一点,但没有任何帮助。我的代码看起来像这样:

let canvas = document.querySelector('.canvas');
let hole = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let holes = [];

let hx =  Math.random() * canvas.width ;
let hy =  Math.random() * canvas.height ;
let radius = 25;

document.querySelector('.start').addEventListener('click', onStartClick);

function onStartClick() {
 // somecode..

    makeHoles();

}

function makeHoles() {
    hole.fillStyle = 'rgb(84, 93, 139)';
    hole.beginPath();
    for (let i = 1; i < 14; i++) {
        hole.moveTo(hx,hy);
        hole.arc(
            hx,
            hy,
            radius,
            0,
            2 * Math.PI,
            true
        );
    }
    hole.stroke();
    hole.fill();
        
    holes.push(hole);

}

2 个答案:

答案 0 :(得分:2)

这不是绘图,因为您没有重新初始化变量。只需将 hxhy 移动到函数中。

let canvas = document.querySelector('.canvas');
let hole = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let holes = [];

let radius = 25;

function onStartClick() {
  // somecode..

  makeHoles();

}

function makeHoles() {
  var hx = Math.random() * canvas.width;
  var hy = Math.random() * canvas.height;
  hole.fillStyle = 'rgb(84, 93, 139)';
  hole.beginPath();
  for (let i = 1; i < 14; i++) {
    hole.moveTo(hx, hy);
    hole.arc(
      hx,
      hy,
      radius,
      0,
      2 * Math.PI,
      true
    );
  }
  hole.stroke();
  hole.fill();

  holes.push(hole);

}
<canvas class="canvas"></canvas>
<button onclick="onStartClick()">Start!</button>

答案 1 :(得分:1)

let canvas = document.querySelector('.canvas');
let hole = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let holes = [];
let radius = 25;

function makeHoles() {
    for (let i = 1; i < 14; i++) {
       let hx =  Math.random() * canvas.width ;
       let hy =  Math.random() * canvas.height ;
        hole.beginPath();
        hole.fillStyle = `rgb(84, 93, 139)`;
        hole.moveTo(hx,hy);
        hole.arc(
            hx,
            hy,
            radius,
            0,
            2 * Math.PI,
            true
        );
        
         hole.stroke();
         hole.fill();
         holes.push(hole);
    }
}

 makeHoles();
<canvas class="canvas"></canvas>