Home > Back-end >  Image crop overlay
Image crop overlay

Time:03-12

On an image upload page I have a preview of the image. I would like create an overlay that shows the image in a rectangle in the middle, with an opaque overlay around the outside of the rectangle.

Similar to this:

enter image description here

I am able to create a div overlay, but I need to reverse the opaque black background to be on the rest of the image but not on the rectangle. This way I can preview to the user what the final product will look like.

Here's what I have:

.wrapper {
  position: relative;
  height: fit-content;
  width: fit-content;
  display: flex;
}

.overlay {
  max-width: 100%;
  height: 100%;
  aspect-ratio: 1 / 1.42;
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  top: 0;
  left: 150px;
  border-radius: 0.5rem;
}
<div >
  <img src="https://picsum.photos/500/300"/>
  <div ></div>
</div>

Requirements

  1. I need to keep the aspect-ratio and relative size of the rectangle consistent.
  2. No magic numbers or fixed width/height unless dynamically calculated per image, these images will be any size or dimensions and the layout needs to be responsive to (nearly) any screen size.
  3. I can't change the markup too much because I'm working with the drag and drop api to move the rectangle within the image wrapper by changing its left and top positions.
  4. I would like to use CSS or Javascript to solve this, not more HTML
  5. Not looking to use object-fit: cover as I need the entire image visible in its native dimensions.

CodePudding user response:

I hope the below code meets your requirements and solves your problem.

.wrapper {
  position: relative;
  height: fit-content;
  width: fit-content;
  display: flex;
}

.overlay {
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 0.5rem;
  width: 100%;
  overflow: hidden;
}
.overlay:before{
    position: absolute;
    content: '';
    aspect-ratio: 1 / 1.42;
    height: 100%;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    box-shadow: 0px 0px 0px 145px rgba(0, 0, 0, 0.4);
  
}
<div >
  <img src="https://picsum.photos/500/300"/>
  <div ></div>
</div>

  • Related