Osa
Osa

Reputation: 1990

CSS/JavaScript to crop image

How to target a specific location on the image to be cropped using css or javascript, simple way without big scripts,

Picture before :
enter image description here


I want the highlighted location on the following image to be viewed :

enter image description here

Not the exact highlighted though, just trying to explain it doesnt has to be from the very top, i want to select specific image scales, AND how to resize is after cropping ?

Upvotes: 15

Views: 17093

Answers (2)

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

Update 2022-05-27: A new property object-view-box will soon make this a lot simpler: https://ishadeed.com/article/css-object-view-box/


One approach is to use an element with overflow: hidden that has the image as a child, which itself is absolutely positioned within the context of the original element. The result being, the size of the overflow: hidden element masks the image.

Here's an example of the approach:

HTML

<div id='crop-the-cats'>
    <img src='https://i.sstatic.net/ArS4Q.jpg'>
</div>​

CSS

#crop-the-cats {
    width: 100px;
    height: 80px;
    overflow:hidden;   
    position:relative;
}

#crop-the-cats img {
    position: absolute;
    top: -60px;
    left: -70px;
}

​See http://jsfiddle.net/Da9CT/

Another approach is to use the image as the background of the image and reposition it using background-position:

HTML

<div id='crop-the-cats'></div>​

CSS

#crop-the-cats {
    width: 100px;
    height: 80px;
    background-image: url(https://i.sstatic.net/ArS4Q.jpg);
    background-position: -50px -60px;
}

​See http://jsfiddle.net/Da9CT/2/

Upvotes: 19

Adaz
Adaz

Reputation: 1665

You can't crop image using javascript / css but you can position it inside an element with overflow hidden: http://jsbin.com/ebenem/1/edit

Let me know if that helps!

Upvotes: 5

Related Questions