CSS/JavaScript 来裁剪图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12789818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:07:44  来源:igfitidea点击:

CSS/JavaScript to crop image

javascripthtmlcssimage

提问by Osa

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

如何使用 css 或 javascript 定位要裁剪的图像上的特定位置,没有大脚本的简单方法,

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 ?

虽然不是确切的突出显示,只是想解释它不必从最顶部开始,我想选择特定的图像比例, 以及如何在裁剪后调整大小?

回答by Josh Davenport

One approach is to use an element with overflow: hiddenthat 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: hiddenelement masks the image.

一种方法是使用overflow: hidden将图像作为子元素的元素,该元素本身绝对定位在原始元素的上下文中。结果是,overflow: hidden元素的大小掩盖了图像。

Here's an example of the approach:

这是该方法的一个示例:

HTML

HTML

<div id='crop-the-cats'>
    <img src='http://i.stack.imgur.com/ArS4Q.jpg'>
</div>?

CSS

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/

?见http://jsfiddle.net/Da9CT/

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

另一种方法是使用图像作为图像的背景并使用background-position以下方法重新定位:

HTML

HTML

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

CSS

CSS

#crop-the-cats {
    width: 100px;
    height: 80px;
    background-image: url(http://i.stack.imgur.com/ArS4Q.jpg);
    background-position: -50px -60px;
}

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

?见http://jsfiddle.net/Da9CT/2/

回答by Adaz

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

您不能使用 javascript / css 裁剪图像,但您可以将其放置在隐藏溢出的元素中:http: //jsbin.com/ebenem/1/edit

Let me know if that helps!

如果有帮助,请告诉我!