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

Viewed 142

I have a blue circle which is rotating around the red circle and moves on canvas continuously in one direction as long as the button is pressed.

Now I want to draw with the red circle while it is moving when the button is pressed (trace of its path). Problems:

when i try to draw on the canvas by not using clearRect(0,0, canvas.width, canvas.height); the blue circle also starts to draw on the canvas while moving which I don't need. Is it possible to draw with one circle and to not draw with another circle on same 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>

1 Answers

All you need to do is call clearRect with the position and dimensions of your blue circle.

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

Or this if you're translating the circle in its local frame of reference:

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