Fun Sai
Fun Sai

Reputation: 1

objectFit cover stretches the image when image width is more than height in React easy crop

issue image
I am using react-easy-crop to crop, zoom an image in my next js app. The image is stretched and cropped to fit the width of the cropper when it's a wide image (width > height) but works perfectly for tall images (height > width), doesn't get stretched nor cropped, dragging I can select the part that I want of the image. Here's my code snippet -

<div
          className={`relative w-full aspect-square rounded-2xl overflow-hidden`}
        >
          {profilePicUrl && (
            <Cropper
              image={profilePicUrl}
              crop={crop}
              zoom={zoom}
              aspect={1}
              cropShape="round"
              showGrid={false}
              onCropChange={setCrop}
              onZoomChange={setZoom}
              onCropComplete={onProfileCropComplete}
              // objectFit={!wideImage ? "cover" : "contain"}
              objectFit="cover"
              style={{
                mediaStyle: {
                  height: wideImage ? "100%" : "fit-content",
                  width: "fit-content",
                  objectFit: "cover",
                },
                cropAreaStyle: {
                  border: "none",
                },
              }}
            />
          )}
        </div>

One roundabout solution I tried is to conditionally set the objectFit attribute as the wide image doesn't get stretched if contained but then the crop area becomes smaller than the parent as shown in the image. And if I specify the mediaStyle then the wide image gets cropped as shown in the image.

I'm trying to achieve the same functionality for wide images as tall images.

Upvotes: 0

Views: 34

Answers (1)

Fun Sai
Fun Sai

Reputation: 1

Figured it out in case someone faces a similar issue. Here's the implementation that worked for me -

<div
      className={`relative sm:rounded-2xl overflow-hidden aspect-square`}
    >
      {profilePicUrl && (
        <Cropper
          image={profilePicUrl}
          crop={crop}
          zoom={zoom}
          aspect={1}
          cropShape="round"
          showGrid={false}
          onCropChange={setCrop}
          onZoomChange={setZoom}
          onCropComplete={onProfileCropComplete}
          objectFit="cover"
          style={{
            cropAreaStyle: {
              border: "none",
            },
            mediaStyle: {
              minWidth: wideImage ? "fit-content" : "100%",
            },
          }}
        />
      )}
    </div>

Upvotes: 0

Related Questions