实现一个平行四边形

29次阅读

共计 1157 个字符,预计需要花费 3 分钟才能阅读完成。

需求如题,想了下用普通的变换如旋转、缩放、位移都是无法实现的。无奈之下谷歌,网友们提供了两个实现方式,第一个是通过 border 的方式,这个比较 tricky;第二种方式很吸引人,原来变换中除了我上面提到的三种方式之外,还有一个 skew,英文意思是歪曲,正是实现平行四边形的利器。
width: 200px;
height: 100px;
background-color: blue;
transform: skew(15deg,0);

接下来我们看看这个 skew 函数怎么工作的从 MDN 网站上看到的介绍 skew(ax, ay) 其中
ax Is an <angle> representing the angle to use to distort the elementalong the abscissa.
字面意思是沿着 x 轴进行变形,那就是相对纵轴变形了;同理 ay 是沿着 y 轴,就是相对 x 轴变形。
还有这么一句话规定了变形的规则
The coordinates of each point are modified by a value proportionate tothe specified angle and the distance to the origin; thus, the fartherfrom the origin a point is, the greater will be the value added it.
这句话告诉我们离原点越远的坐标改变越大,而且这种改变是等比例的。
我们了解下屏幕坐标系长什么样子。

可以看到原点在左上角,x 轴向右延伸,y 轴向下延伸。回头看上面的例子 transform: skew(15deg,0); 中第一个参数表示沿着 x 轴的变化,就是相对 y 轴的变化,这个变化值是 15deg,正好就是我们画出的效果图。
再来看看上面提到的用 border 如何实现。实现思路是通过拼两个三角形来模拟平行四边行,而矩形又可以通过 border 来实现,我们先看看如何实现一个三角形

如图可以隐藏另外三个边来实现一个三角形,两个三角形就可以形成一个平行四边形三角形的斜率可以通过宽高比不同来实现。
<div class=”orgram”></div>
.orgram:before {
content: “”;
display:block;
position: absolute;
border: 10px solid transparent;
border-top-color: red;
height: 0px;
width: 0px;
}

.orgram:after {
content: “”;
display:block;
position: absolute;
left: 18px;
margin-top:-10px;
border: 10px solid transparent;
border-bottom-color: red;
height: 0px;
width: 0px;
}

正文完
 0