Monday, June 13, 2022

Clipping an image

Step 1: In order to clip an image, we use the CSS property clip-path which expects a shape like a circle, ellipse or a polygon. There are CSS functions corresponding to these shapes, 

polygon function expects the vertices of polygon in a clockwise direction.

Example 1:

clip-path: polygon(25% 0%100% 0%75% 100%0% 100%); 

Vertex 1 --25% 0%  refers to move 25% in X direction (horizontal axis) and  0% in Y direction (vertical axis) -- Marked red in the image below.

Vertex 2 --100% 0% refers to move 100% in X direction and 0% in Y direction. -- Marked green in the image below.

Vertex 3 -- 75% 100% refers to move 75% in X direction and 100% in Y direction -- Marked yellow in the image below.

Vertex 4 -- 0% 100% refers to move 0% in X direction and 100% in Y direction -- Marked blue in the image below.


Example 2: 

clip-path: circle(50% at 50% 50%);

means to clip a circle shape with 50% radius (50% of width the current image) at 50% 50% (which refers to the center of the circle i.e 50% in X direction and 50% in Y direction--Marked green in the image below).

NOTE: Make sure the image which is being clipped is a square means the width and height must be same.


Example 3: 

clip-path: ellipse(25% 40% at 50% 50%);


Similar to circle 50% 50% refers the center (marked as orange in the image below) and 25% refers to distance of the major axis (marked red in the image below) and 40% distance of the minor axis (marked green in the image below).





Code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Learn clip-path in CSS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      img {
        height: 500px;
        clip-path: polygon(25% 0%, 100% 0%, 75% 100%, 0% 100%);
      }
    </style>
  </head>
  <body>
    <img src="./Leonardo.webp" alt="Leonardo" />
  </body>
</html>

Result:



Reference: Newbies can use the following websites to get the polygon coordinates of mostly used geometric shapes from the following resources:


1. https://bennettfeely.com/clippy/


2. https://www.cssportal.com/css-clip-path-generator/


No comments:

Post a Comment