我怎样才能在 canvas 上绘制一个对象并在不绘制的情况下移动该对象?

How can i draw on canvas with an object and move the object without drawing?

我有一个蓝色圆圈,它围绕着红色圆圈旋转,只要按下按钮,它就会朝一个方向连续canvas移动。

现在我想在按下按钮时移动的红色圆圈(其路径的轨迹)进行绘制。 问题:

当我尝试通过不使用 clearRect(0,0, canvas.width, canvas.height) 来绘制 canvas 时;移动时蓝色圆圈也开始在 canvas 上绘制,我不需要。 是否可以在同一个圆上画一个圆而不画另一个圆canvas?

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let positionX = 100;
let positionY = 100;
let X = 50;
let Y = 50;
let angle = 0;
let mouseButtonDown = false;

document.addEventListener('mousedown', () => mouseButtonDown = true);
document.addEventListener('mouseup', () => mouseButtonDown = false);

function circle(){
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(X, Y, 20, 0, Math.PI*2);
    ctx.closePath();
    ctx.fill();
}
function direction(){
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.arc(positionX + X, positionY + Y, 10, 0, Math.PI*2);
    ctx.closePath();
    positionX = 35 * Math.sin(angle);
    positionY = 35 * Math.cos(angle);
    ctx.fill();   
}
function animate(){
    if (mouseButtonDown) {
        X += positionX / 10;
        Y += positionY / 10;
    } else {
        angle += 0.1;
    }
    ctx.clearRect(0,0, canvas.width, canvas.height);
    circle();
    direction();
    requestAnimationFrame(animate);   
}
animate();
#canvas1{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="canvas1"></canvas>
    
    <script src="script.js"></script>
</body>
</html>

您需要做的就是使用蓝色圆圈的位置和尺寸调用 clearRect。

ctx.clearRect(blueCircle.x, blueCircle.y, blueCircle.diameter, blueCircle.diameter);

或者,如果您在其局部参考系中平移圆,则为:

ctx.clearRect(blueCircle.x - blueCircle.radius, blueCircle.y - blueCircle.radius, blueCircle.diameter, blueCircle.diameter);