How to fill a shape on mouseover using canvas?

by cortez.connelly , in category: Javascript , 3 months ago

How to fill a shape on mouseover using canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 3 months ago

@cortez.connelly 

To fill a shape on mouseover using the canvas element in HTML5, you can use JavaScript to listen for the 'mouseover' event on the canvas element and then redraw the shape with a different color or fill style.


Here is an example code snippet to demonstrate how to fill a rectangle on mouseover using canvas:


HTML:

1
<canvas id="myCanvas" width="200" height="200"></canvas>


JavaScript:

 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
// Get the canvas element
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Initial rectangle properties
let rectX = 50;
let rectY = 50;
let rectWidth = 100;
let rectHeight = 50;

// Function to draw the rectangle
function drawRect() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'blue';
  ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
}

// Event listener for mouseover
canvas.addEventListener('mouseover', function(event) {
  ctx.fillStyle = 'red';
  ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
});

// Event listener for mouseout
canvas.addEventListener('mouseout', function(event) {
  ctx.fillStyle = 'blue';
  ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
});

// Initial draw of the rectangle
drawRect();


In this example, when the mouse is over the canvas, the rectangle will be filled with a red color. When the mouse is not over the canvas, the rectangle will be filled with a blue color. The drawRect() function is called to initially draw the blue rectangle on the canvas.