user7470319
user7470319

Reputation:

Reactjs: how to minimally crop an image to a certain aspect ratio in client side?

In, I'd like to crop an image, in a minimal fashion, so that it fits a given aspect ratio.

Example: given an image of, say, 3038 x 2014 px, I want to crop it to have a 1:2 aspect ratio. The resulting image would then be 3021 x 2014 px, cropped from the, say, center of the original image.

Upvotes: 1

Views: 2082

Answers (2)

Rik
Rik

Reputation: 3596

I've written an article on cropping images with JavaScript to fit a certain aspect ratio (in the center as you requested).

This will create a clone of the original image given the aspect ratio supplied. The function we create in the article can be called like this:

crop('url/to/image.jpg', 1).then(canvas => {
    // canvas is a new image canvas based
    // on the source image and the supplied aspect ratio
})

// or use async/await
const canvas = await crop('url/to/image.jpg', 1);

I've also set up a Codepen demo

Upvotes: 2

Steven Lacks
Steven Lacks

Reputation: 904

You can use CSS to crop an image, it's called "clipping" in CSS and the property is clip.

clip: rect(top-left-pixel-x, top-left-pixel-y, bottom-right-pixel-x, bottom-right-pixel-y);

If this weren't responsive, you'd just put in the pixels you want manually. The image is 3/2 so you need to enter in what part of the image you want to show.

Let's do the middle horizontal section here.

clip: rect(0, 1007px,  2014px, 2014px);

Of course, this becomes harder when you're doing responsive design. You'll need to calculate the positions off the current height and width..

  componentDidMount() {
    const height = this.divElement.clientHeight;
    const width = this.divElement.clientWidth;
    this.setState({ style: `clip: rect(0, ${heigh/3}, width, ${2*height/3}` ); 

    // Note: if the starting img is always 3:2 ratio, the final value could be the width because 3:2 -> 2:! has that natural property, but this code is more flexible
  }

  render() {
    return (
      <img src="[your file source]" style={style}/>
    )
  }

Upvotes: 0

Related Questions