How to drag a drawn circle within a canvas?

Member

by daisha , in category: Javascript , 4 months ago

How to drag a drawn circle within a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 4 months ago

@daisha 

To drag a drawn circle within a canvas using JavaScript, you can follow these steps:

  1. Create a canvas element in your HTML file:
1
<canvas id="myCanvas" width="500" height="500"></canvas>


  1. Get the canvas element and its context in your JavaScript file:
1
2
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');


  1. Draw a circle on the canvas:
1
2
3
4
5
6
7
8
function drawCircle(x, y, radius) {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = 'blue';
    ctx.fill();
    ctx.closePath();
}
drawCircle(50, 50, 20);


  1. Add event listeners to handle dragging the circle:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
let isDragging = false;
let offsetX, offsetY;

canvas.addEventListener('mousedown', (e) => {
    const rect = canvas.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;
    
    if (Math.sqrt((mouseX - 50)**2 + (mouseY - 50)**2) <= 20) {
        isDragging = true;
        offsetX = mouseX - 50;
        offsetY = mouseY - 50;
    }
});

canvas.addEventListener('mousemove', (e) => {
    if(isDragging) {
        const rect = canvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;
        
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawCircle(mouseX - offsetX, mouseY - offsetY, 20);
    }
});

canvas.addEventListener('mouseup', () => {
    isDragging = false;
});


Now you can click and drag the circle within the canvas. When you click inside the circle, it will start dragging and follow your mouse movements until you release the mouse button.