即时从中心裁剪图像 - Javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4712950/
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-25 14:37:16  来源:igfitidea点击:

cropping images from center on the fly - Javascript?

javascriptjquerycrop

提问by terrid25

I have a bunch of images, that are various sizes, in terms of width and height.

我有一堆图像,它们的宽度和高度各不相同。

Some are square, some are rectangle, but I'd like all of them to be width and height of my choice.

有些是方形的,有些是矩形的,但我希望所有这些都是我选择的宽度和高度。

I know I can use the width="" and height="" in the

我知道我可以在

So, what I was looking for, is a possible javascript solution, maybe using jQuery, that will crop the images from center on the fly?

那么,我正在寻找的是一种可能的 javascript 解决方案,也许使用 jQuery,它会动态地从中心裁剪图像?

Is this possible?

这可能吗?

回答by Bobby Hyman

You can position the images within a container using CSS. Then ensure overflow: hidden is set on that container.

您可以使用 CSS 在容器中放置图像。然后确保在该容器上设置了 overflow: hidden 。

For example:

例如:

<style>
.container     { position: relative; overflow: hidden; }
.container img { position: absolute; }
</style>

<div class="container">
    <img src="..."/>
</div>

<script type="text/javascript">
$image = $('.container img');
width = $image.width();
height = $image.height();

$image.css({
    left: 0 - (width / 2),
    top: 0 - (height / 2)
});
</script>

回答by Tom Gullen

<div style="width:200px;height:200px;overflow:hidden;position:relative;">
    <img src="example.png" style="width:200px;height:200px;position:absolute;left:-10px;top:-10px;" />
</div>

Something like that! By setting the left/top properties of it's position you can simulate a crop. The above example will take 10px off the top and left of the image. This example assumes the image is 200px by 200px, obviously edit values for your image.

类似的东西!通过设置它的位置的 left/top 属性,您可以模拟裁剪。上面的示例将从图像的顶部和左侧减去 10px。此示例假定图像为 200 像素 x 200 像素,显然是为您的图像编辑值。

You may need to reposition the container div so that the image looks like it remains in the same place.

您可能需要重新定位容器 div,以便图像看起来保持在同一位置。