How to place a image inside a square of canvas?

Member

by adan , in category: Javascript , 4 months ago

How to place a image inside a square of canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 4 months ago

@adan 

To place an image inside a square canvas, you can use HTML5 and CSS. Here's how you can do it:

  1. Create a square canvas element in your HTML file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
    <title>Image in Square Canvas</title>
    <style>
        .canvas {
            width: 200px;
            height: 200px;
            border: 1px solid black;
            position: relative;
        }
        .image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
    <div class="canvas">
        <img src="image.jpg" class="image">
    </div>
</body>
</html>


  1. Replace "image.jpg" with the path to your image file.
  2. Save the file and open it in a web browser to see the image inside the square canvas.


You can adjust the width and height of the canvas element to create a square of any size. The CSS object-fit: cover; property ensures that the image fills the square canvas completely without stretching it.