如何创建圆形对象并将其推入数组?

时间:2019-02-18 16:07:44

标签: javascript html5

这是一个作业问题。我需要在HTML5画布中创建一个圆圈,以便每次单击都会创建一个颜色随机的圆圈。圆的中心是单击鼠标的位置。但是,如果新创建的圆圈与已绘制的任何其他圆圈重叠,则这些圆圈将消失,而新圆圈将保留。我认为可以重叠的逻辑。我的问题是如何跟踪画布上绘制的所有圆?

(function(doc) {
  var canvas = doc.getElementById("testCanvas");
  var context = canvas.getContext("2d");

  // Click event handler
  canvas.onclick = function(e) {
    // Creating array for circles
    var circles = [];

    // Creating a circle with random color and a given radius at the mouse click
    var nextColor = randomColor();
    context.fillStyle = nextColor;
    context.beginPath();
    context.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI);
    context.fill();
    context.closePath();

    // Creating circle object
    var circle = {
      x_coord: e.clientX,
      y_coord: e.clientY,
      color: nextColor,
      visible: true
    };

    // Pushing circle object into the array of circles
    circles.push(circle);

    //document.getElementById("demo").innerHTML = circles;
    console.log(circles);
  };
})(document);
<canvas id="testCanvas" />

1 个答案:

答案 0 :(得分:0)

我在您的代码中看到的唯一真正的问题是,您正在初始化处理程序 内的circles数组。这意味着您的圆形数组的最大长度为1,因为每次点击都会对其进行初始化。

相反,只需将以下内容移至点击处理程序之外,即可初始化一次圆数组。

var circles = [];

示例:

(function (doc) {
  var canvas = doc.getElementById("testCanvas");
  var context = canvas.getContext("2d");

  // Creating array for circles 
  var circles = [];

  // Click event handler
  canvas.onclick = function (e) {

    // Creating a circle with random color and a given radius at the mouse click
    var nextColor = "black";
    context.fillStyle = nextColor;
    context.beginPath();
    context.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI);
    context.fill();
    context.closePath();

    // Creating circle object
    var circle = {
      x_coord: e.clientX, y_coord: e.clientY, color:
        nextColor, visible: true
    };

    // Pushing circle object into the array of circles
    circles.push(circle);

    console.log(circles);
  }

})(document);
canvas {
 width: 100vw;
 height: 100vh;
}
<canvas id="testCanvas" />