初始状态生成十个随机点
每按下一次按钮,点数+1
做了判断,让随机点不会超过画布边缘
效果:
JS代码如下:
// 获取“Add Circle”按钮元素
var addCircleButton = document.getElementById("addCircleButton");
// 监听按钮点击事件
addCircleButton.addEventListener("click", function() {
// 生成新圆形的位置,并确保不超出画布边缘
var x = Math.random() * (canvas.width - radius * 2) + radius;
var y = Math.random() * (canvas.height - radius * 2) + radius;
// 添加新圆形到数组
circles.push({x: x, y: y});
numCircles++;
// 绘制新圆形
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
});
// 获取画布和上下文
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 定义圆形数组
var circles = [];
// 定义圆形数量和半径
var numCircles = 10;
var radius = 5;
// 定义选中的圆形数组
var selectedCircles = [];
// 生成圆形数组
for (var i = 0; i < numCircles; i++) {
var x = Math.random() * (canvas.width - radius * 2) + radius;
var y = Math.random() * (canvas.height - radius * 2) + radius;
// 确保圆形不超出边缘
if (x < radius) {
x = radius;
} else if (x > canvas.width - radius) {
x = canvas.width - radius;
}
if (y < radius) {
y = radius;
} else if (y > canvas.height - radius) {
y = canvas.height - radius;
}
circles.push({x: x, y: y});
}
// 绘制圆形
for (var i = 0; i < numCircles; i++) {
ctx.beginPath();
ctx.arc(circles[i].x, circles[i].y, radius, 0, Math.PI * 2);
ctx.fill();
}
// 监听鼠标点击事件
canvas.addEventListener("mousedown", function(event) {
// 获取鼠标点击位置
var mouseX = event.clientX - canvas.offsetLeft;
var mouseY = event.clientY - canvas.offsetTop;
// 查找与鼠标点击位置最近的圆形
var closestCircle = null;
var closestDistance = Infinity;
for (var i = 0; i < numCircles; i++) {
var distance = Math.sqrt(Math.pow(mouseX - circles[i].x, 2) + Math.pow(mouseY - circles[i].y, 2));
if (distance < closestDistance) {
closestCircle = circles[i];
closestDistance = distance;
}
}
// 如果已经有一个圆形被选中,则绘制连接线
if (selectedCircles.length == 1) {
// 添加新的选中圆形
selectedCircles.push(closestCircle);
// 绘制连接线
ctx.beginPath();
ctx.strokeStyle = "green";
ctx.moveTo(selectedCircles[0].x, selectedCircles[0].y);
ctx.lineTo(selectedCircles[1].x, selectedCircles[1].y);
ctx.stroke();
// 清空选中的圆形数组
selectedCircles = [];
}
// 否则,将当前圆形添加到选中的圆形数组
else {
selectedCircles.push(closestCircle);
}
});
如需完整代码,请mail 2938133585@qq.com
H