How to overlap shapes on top of each other in canvas?

Member

by mac , in category: Javascript , 4 months ago

How to overlap shapes on top of each other in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 4 months ago

@mac 

To overlap shapes on top of each other in a canvas, you can draw each shape individually and then adjust their position to overlap. Here is an example using HTML5 canvas and JavaScript to draw two rectangles on top of each other:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
  <title>Overlap Shapes on Canvas</title>
</head>
<body>
  <canvas id="myCanvas" width="200" height="200"></canvas>
  
  <script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // Draw first rectangle
    ctx.fillStyle = 'blue';
    ctx.fillRect(50, 50, 100, 100);
    
    // Draw second rectangle on top of the first one
    ctx.fillStyle = 'red';
    ctx.fillRect(75, 75, 100, 100);
  </script>
</body>
</html>


In this example, we first draw a blue rectangle with the fillRect method at position (50, 50) with a width and height of 100. Then, we draw a red rectangle on top of the blue one by adjusting its position to (75, 75).


You can adjust the position, size, color, and shape of the overlapping objects as needed to achieve the desired effect.