裁剪图像,然后拉伸以填充可用空间

Crop image and then stretch to fill available space

本文关键字:填充 空间 图像 然后 裁剪      更新时间:2023-09-26

我正在尝试从 url 裁剪图像,然后将裁剪后的图像拉伸到可用空间。

<div style="width:300px; height:400px;">
  <img style="width:100%; height:100%;" src="http://www.gravatar.com/avatar/eb95aa803f8c6d536afc87bf8d641ed4?s=128&amp;d=identicon&amp;r=PG" />
</div>

这将适当地拉伸图像,但我不知道如何裁剪它。我尝试使用clip:rect(0px,60px,200px,0px);但图像将首先拉伸到可用空间,然后应用剪辑,因此它对我不起作用。

编辑 - jsfiddle: http://jsfiddle.net/bjMp6/

例如,我想尝试裁剪头部,然后拉伸头部

在没有第二个div的情况下完成Yoshi的想法

div
{
    width:300px; 
    height:400px;
    border:1px solid #333;
    overflow:hidden;
    position:relative;
}
img
{
    width:300%; 
    height:300%;
    position:absolute;
    top:0;
    left:-50%;
}

添加了边框只是为了查看包含的div。 这样,您无需知道容器的暗淡,但是要裁剪图像,您必须使用任何解决方案来播放数字,除非所有图像都具有相同的相对构图,即头像或类似的东西。

这是您观看乐趣的小提琴。

此外,随着容器的增长/缩小,您的图像将保留相同的裁剪和位置。

我做了一个小提琴来说明画布解决方案:

http://jsfiddle.net/dystroy/mDy24/

这是 html :

   <div id=theimg style="width:300px; height:400px;">
          <canvas id=thecanvas style="width:100%;height:100%;">
   </div>​

和 js :

   var img = new Image();
   img.src = "http://www.gravatar.com/avatar/eb95aa803f8c6d536afc87bf8d641ed4?s=128&amp;d=identicon&amp;r=PG";
   img.onload = function() {
          var can = document.getElementById('thecanvas');
          var con = can.getContext("2d");
          console.log(con);
          con.drawImage(img, 0, 0, 50, 50, 0, 0, can.width, can.height);
   }​