“解决方案”基本上只是在坐标空间方面更好地理解 css rect 属性。
我对如何确定 css 剪辑矩形出现的位置感到困惑。一旦您意识到就 css rect 而言,“坐标空间”是被裁剪元素的尺寸 (E),答案实际上很简单,并且您始终可以将 E 视为其左上角具有坐标 x=0,y=0。
假设我们有一个元素 E,它的高度为 200,宽度为 300。我们可以这样描述它
E= {x:0, y:0, width:300, height:200}
它的 x 和 y 坐标,就我们而言,在绘制裁剪矩形的 TRBL 值时是 0, 0。所以让我们考虑裁剪矩形,这样定义的示例
C= {x:30, y:30, width:150, height:150}
由于 C.x 和 C.y 指的是 E 的坐标空间,而 E.x 和 E.y 总是 0,我们可以完全忽略 E.x 和 E.y,在所有情况下。事实上,除非我们关心将 C(剪切矩形)约束到 E,否则我们可以完全消除 E 的所有知识,并使用如下方法将 C 转换为 css rect 声明。
function toCssRect(rectangle)
{
var left= parseInt(rectangle.x)
, right= parseInt(left + rectangle.width)
, top= parseInt(rectangle.y)
, bottom= parseInt(top + rectangle.height);
return 'rect(' + top + 'px ' + right + 'px ' + bottom + 'px ' + left +'px)';
}
因此,使用以下 HTML 标记(将 img 元素视为 E)
<div class='.clipComponent'>
<div id="contentClipper" class=".clipContent'>
<img src="whatever.jpg"/>
</div>
</div>
... 和 CSS
.clipComponent {position:relative}
.clipContent {position:absolute; clip:rect(auto);}
...我们将有一个未剪辑的图像(因为 .clipContent 将适应 img 的大小,因为我们用 auto 定义了它)。现在为了剪辑它,我们可以将 C(上面定义的)传递给 toCssRect 函数并将其应用到 .clipContent div,就像这样
var clipDiv= document.getElementById('contentClipper')
, clipRect= {x:10, y:10, width:100, height:20};
clipDiv.style.clip= toCssRect(clipRect);
我们到了。这样做的好处是可以通过添加值来移动矩形
到它的 x 和 y 属性,或者通过修改其宽度和高度属性来扩大和缩小矩形。每次修改后,将矩形转换为 css rect 声明,并将 is 设置为 clip 的值。这非常适合制作动画。
如果你想实现自己的矩形类,请注意,至少在 Safari 和 Chrome 中,如果你实现 toString 以返回 toCssRect 方法的结果,你可以只将矩形分配给元素样式对象的剪辑属性- 为了便于说明,请考虑下面的对象字面量:
var clipRect=
{
x:30,
y:40,
width:10,
height:30,
toString: function ()
{
return toCssRect(this);
},
translate: function (dx, dy)
{
this.x+= dx || 0;
this.y+= dy || 0;
return this;
}
}
现在您可以非常清晰地制作动画和编码(假设上面定义了对象和函数)
setInterval(function ()
{
// translate will add 1px to the value of the rectangles x position,
// (moving it down) and then return a reference to the clipRect object.
// When you assign the clipRect object to the divs style object
// JavaScript will attempt to convert the clipRect object to a primitive,
// which will invoke toString and return the css string- nice and clean
clipDiv.style.clip= clipRect.translate(1, 0);
}, 500);
希望这一切都有意义!