cropping images from center on the fly - Javascript?

故事扮演 提交于 2019-12-11 02:28:13

问题


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?

Is this possible?


回答1:


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

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>



回答2:


<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.

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



来源:https://stackoverflow.com/questions/4712950/cropping-images-from-center-on-the-fly-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!