关于css3:每天一个小技巧CSS-clippath-的妙用

0次阅读

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

CSS 的 clip-path 属性是 clip 属性的升级版,它们的作用都是对元素进行“剪裁”,不同的是 clip 只能作用于 positionabsolutefixed 的元素且剪裁区域只能是正方形,而 clip-path 更加弱小,能够以任意形态去裁剪元素,且对元素的定位形式没有要求。基于这样的个性,clip-path 罕用于实现一些炫酷的动画成果。

比方:

视差广告成果:

实现请参考:CodePen

菜单栏弹出成果:

实现请参考:CodePen

Clip Path 分类

clip-path 有几大类,别离为:

  • basic-shape: 根本图形,包含 inset()circle()ellipse()polygon()
  • clip-source: 通过 url() 办法援用一段 SVG 的 <clipPath> 来作为剪裁门路
  • geometry-box: 独自应用时会将指定框的边缘作为剪裁门路,或者配合 basic-shape 应用,用于定义剪裁的 参考框(Reference Box)(因为该属性浏览器反对度比拟低,本文暂不探讨)

一、Basic Shape

1. Inset

inset() 用于定义一个插进的矩形,即被剪裁元素外部的一块矩形区域。

参数类型:inset(<shape-arg>{1,4} [round <border-radius>]? )

其中 shape-arg 别离为矩形的上右下左顶点到被剪裁元素边缘的间隔(和 marginpadding 参数相似),border-radius 为可选参数,用于定义 border 的圆角。

DEMO:

html:

<img class="img inset" src="http://source.unsplash.com/random/1000x1000" />

css:

.inset {clip-path: inset(0);

  &:active {clip-path: inset(100px 200px 10% 20% round 20px);
  }
}

2. Circle

circle() 用于定义一个圆。

参数类型:circle([<shape-radius>]? [at <position>]? )

其中 shape-radius 为圆形的半径,position 为圆心的地位。

如果 shape-radius 为百分比,则 100% 相当于:

sqrt(width^2+height^2)/sqrt(2)

widthheight别离为被剪裁元素的宽高。

DEMO:

html:

<img class="img circle" src="http://source.unsplash.com/random/1000x1000" />

css:

.circle {clip-path: circle(100px at center);

  &:hover {clip-path: circle(50% at center);
  }
}

3. Ellipse

ellipse() 用于定义一个椭圆。

参数类型:ellipse([<shape-radius>{2}]? [at <position>]? )

其中 shape-radius 为椭圆 x、y 轴的半径,position 为椭圆核心的地位。

DEMO:

html:

<h2>Ellipse (click)</h2>
<div class="img-box">
  <img class="img ellipse" src="http://source.unsplash.com/random/1000x1000" />
</div>

css:

.ellipse {clip-path: ellipse(200px 500px at 50% 50%);

  &:active {clip-path: ellipse(500px 500px at 50% 50%);
  }
}

4. Polygon

polygon() 用于定义一个多边形。

参数类型:polygon([<fill-rule>,]? [<shape-arg> <shape-arg>]# )

其中 fill-rule 为填充规定,即通过一系列点去定义多边形的边界。

DEMO:

html:

<img class="img polygon" src="http://source.unsplash.com/random/1000x1000" />

css:

.polygon {clip-path: polygon(0% 50%, 50% 0%, 100% 50%, 50% 100%);

  &:active {transform: rotate(720deg);
    clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
  }
}

二、Clip Source

即通过援用一个 svg 的 clipPath 元素来作为剪裁门路。比方,应用在 <clipPath> 中定义一个圆:

html:

<svg>
  <defs>
    <clipPath id="svgCircle">
      <circle cx="500" cy="500" r="400" />
    </clipPath>
  </defs>
</svg>

<img class="img svg-circle" src="http://source.unsplash.com/random/1000x1000" />

css:

.svg-circle {clip-path: url("#svgCircle");
}

成果:

Clippy

如果感觉本人去计算和绘制一个图形太麻烦,能够应用 clippy 这个在线 clip-path 绘制工具,外面蕴含了大部分罕用的图形,也反对可视化绘制自定义图形。

Clippy:

每天一个小技巧(Tricks by Day),质变引起量变,心愿你和我一起每天多学一点,让技术乏味一点。

所有示例将会汇总到我的 tricks-by-day github 我的项目中,欢送大家莅临指导 ????

正文完
 0