这是一个家庭作业问题。我需要在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,因为每次单击都会重新初始化。
而是通过将以下内容移动到单击处理程序外部来初始化圆形数组。
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" />