老板:别人有的,我们也要有!
效果如下,每一只动物都是一块一块碎片组成的,并且每一次切换的时候,碎片都有一种重组动画效果,如下:
实现起来不难,分享给大家
一探究竟
进到这个网站中看,可以看到每一只动物都是由无数个碎片DOM节点叠加而成的,而这些碎片是怎么画的呢,可以看出用了两个样式:
-
clip-path:碎片形状的绘制
-
background-color:碎片背景颜色
如果对 clip-path
这个样式感兴趣的,可以去 MDN 文档上看~
碎片数据获取
既然我们知道了这些动物是由碎片叠加而来,那么我们可以去获取每一个碎片的 clip-path、background-color
,并存入到一个数组中
这对于我们前端来说并非难事,只需要通过 DOM 操作即可收集数据,代码如下
将上面代码复制到网站的控制台中去进行运行,即可或者这只动物的所有碎片的数据
接着你如果想获取多个动物的碎片数据,无非就是切换一个动物,就执行一下这段代码,这样就可以获取到很多只动物的碎片数据了~
我将这些数据集合收集到 data.json
文件中
动物绘制
有了数据之后我们就可以开始绘制动物了,只需要通过简单的循环以及样式赋值,即可绘制成功
切换动画
接下来需要完成动画切换,以及切换动画,其实也不难,只需要给每个碎片加上过渡动画,并且增加一个按钮实现数据索引切换即可
完整源码
获取碎片数据代码
1let shards = document.querySelectorAll('.shard')
2const res = []
3shards.forEach(ele => {
4 const allStyles = window.getComputedStyle(ele)
5 res.push({
6 clipPath: allStyles.getPropertyValue('clip-path'),
7 backgroundColor: allStyles.getPropertyValue('background-color')
8 })
9})
10console.log(JSON.stringify(res))
1<template>
2 <Button @click="changeAnimal">切换</Button>
3 <div class="animal-container">
4 <template v-for="(item, index) in currentData" :key="index">
5 <div
6 class="clip-item"
7 :style="{
8 backgroundColor: item.backgroundColor,
9 clipPath: item.clipPath,
10 transitionDelay: `${index * 15}ms`,
11 }"
12 ></div>
13 </template>
14 </div>
15</template>
16
17<script lang="ts" setup>
18import { ref } from 'vue';
19import { Button } from 'ant-design-vue';
20import data from './data.json';
21
22const currentIndex = ref(0);
23const currentData = ref(data[0]);
24const length = data.length;
25const changeAnimal = () => {
26 currentIndex.value++;
27 // 索引到最后了,重置为 0
28 if (currentIndex.value >= length) {
29 currentIndex.value = 0;
30 }
31 currentData.value = data[currentIndex.value];
32};
33</script>
34
35<style scoped lang="less">
36.animal-container {
37 width: 800px;
38 height: 600px;
39 position: relative;
40
41 .clip-item {
42 position: absolute;
43 width: 100%;
44 height: 100%;
45
46 // 动画过渡效果
47 transition-property: all;
48 transition-duration: 1000ms;
49 transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
50 }
51}
52</style>
个人笔记记录 2021 ~ 2025