2

我正在尝试从 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/

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

4

2 回答 2

1

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

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);
   }​
于 2012-04-26T15:22:17.517 回答
1

在没有第二个 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。这样,您将不需要知道容器的暗淡,但是要裁剪图像,您必须使用任何解决方案来处理数字,除非所有图像都具有相同的相对组成,即头像或类似的东西。

这是您观看乐趣的小提琴

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

于 2012-04-26T15:42:04.013 回答