How to toggle a circle on a canvas?

Member

by dana , in category: Javascript , 2 months ago

How to toggle a circle on a canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 2 months ago

@dana 

To toggle a circle on a canvas, you can use JavaScript to create an HTML canvas element and draw a circle on it. Then, you can use an event listener to detect a mouse click on the canvas and toggle the visibility of the circle.


Here is an example code snippet that demonstrates how to toggle a circle on a canvas:

 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
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Circle on Canvas</title>
<style>
    canvas {
        border: 1px solid black;
    }
</style>
</head>
<body>
    <canvas id="myCanvas" width="200" height="200"></canvas>
    <script>
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');
        let circleVisible = false;

        function drawCircle() {
            ctx.beginPath();
            ctx.arc(100, 100, 50, 0, 2 * Math.PI);
            ctx.fillStyle = 'blue';
            ctx.fill();
        }

        function toggleCircle() {
            if (circleVisible) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                circleVisible = false;
            } else {
                drawCircle();
                circleVisible = true;
            }
        }

        canvas.addEventListener('click', toggleCircle);
    </script>
</body>
</html>


In this code, the drawCircle function draws a blue circle on the canvas at the center (100, 100) with a radius of 50. The toggleCircle function clears the canvas if the circle is already visible, or draws the circle if it is not visible. The event listener on the canvas triggers the toggleCircle function when the canvas is clicked, effectively toggling the visibility of the circle.