要使两个圆对象在画布内可移动,可以通过以下步骤实现:
arc()
方法指定圆心坐标、半径和起始角度、结束角度来绘制圆。clearRect()
方法清除之前的绘制,然后重新绘制更新后的圆对象位置。以下是一个示例代码,实现了两个圆对象的可移动功能:
<!DOCTYPE html>
<html>
<head>
<title>Move Circles</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// 获取画布和上下文
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 定义圆对象
var circle1 = { x: 50, y: 50, radius: 20 };
var circle2 = { x: 150, y: 150, radius: 30 };
// 记录鼠标按下的位置
var mouseDown = false;
var mouseX, mouseY;
// 绘制圆对象
function drawCircles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(circle1.x, circle1.y, circle1.radius, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.beginPath();
ctx.arc(circle2.x, circle2.y, circle2.radius, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
}
// 鼠标按下事件
canvas.addEventListener("mousedown", function (e) {
mouseDown = true;
mouseX = e.clientX - canvas.offsetLeft;
mouseY = e.clientY - canvas.offsetTop;
});
// 鼠标移动事件
canvas.addEventListener("mousemove", function (e) {
if (mouseDown) {
var newMouseX = e.clientX - canvas.offsetLeft;
var newMouseY = e.clientY - canvas.offsetTop;
var deltaX = newMouseX - mouseX;
var deltaY = newMouseY - mouseY;
circle1.x += deltaX;
circle1.y += deltaY;
circle2.x += deltaX;
circle2.y += deltaY;
mouseX = newMouseX;
mouseY = newMouseY;
drawCircles();
}
});
// 鼠标释放事件
canvas.addEventListener("mouseup", function () {
mouseDown = false;
});
// 绘制初始圆对象
drawCircles();
</script>
</body>
</html>
这段代码创建了一个400x400像素的画布,并在画布上绘制了两个圆对象。通过监听鼠标事件,实现了圆对象的移动功能。当鼠标按下并移动时,计算鼠标移动的距离,并更新圆对象的位置,然后重新绘制圆对象。
领取专属 10元无门槛券
手把手带您无忧上云