老板要求我實(shí)現(xiàn)一只碎片化效果的鳥,難得倒我?
老板:別人有的,我們也要有!
效果如下,每一只動(dòng)物都是一塊一塊碎片組成的,并且每一次切換的時(shí)候,碎片都有一種重組動(dòng)畫效果,如下:
實(shí)現(xiàn)起來不難,分享給大家!
一探究竟
進(jìn)到這個(gè)網(wǎng)站中看,可以看到每一只動(dòng)物都是由無數(shù)個(gè)碎片DOM節(jié)點(diǎn)疊加而成的,而這些碎片是怎么畫的呢,可以看出用了兩個(gè)樣式:
- clip-path:碎片形狀的繪制
- background-color:碎片背景顏色
如果對(duì) clip-path 這個(gè)樣式感興趣的,可以去 MDN 文檔上看~
碎片數(shù)據(jù)獲取
既然我們知道了這些動(dòng)物是由碎片疊加而來,那么我們可以去獲取每一個(gè)碎片的 clip-path、background-color,并存入到一個(gè)數(shù)組中。
這對(duì)于我們前端來說并非難事,只需要通過 DOM 操作即可收集數(shù)據(jù),代碼如下:
將上面代碼復(fù)制到網(wǎng)站的控制臺(tái)中去進(jìn)行運(yùn)行,即可或者這只動(dòng)物的所有碎片的數(shù)據(jù):
接著你如果想獲取多個(gè)動(dòng)物的碎片數(shù)據(jù),無非就是切換一個(gè)動(dòng)物,就執(zhí)行一下這段代碼,這樣就可以獲取到很多只動(dòng)物的碎片數(shù)據(jù)了~
我將這些數(shù)據(jù)集合收集到 data.json 文件中:
動(dòng)物繪制
有了數(shù)據(jù)之后我們就可以開始繪制動(dòng)物了,只需要通過簡(jiǎn)單的循環(huán)以及樣式賦值,即可繪制成功
切換動(dòng)畫
接下來需要完成動(dòng)畫切換,以及切換動(dòng)畫,其實(shí)也不難,只需要給每個(gè)碎片加上過渡動(dòng)畫,并且增加一個(gè)按鈕實(shí)現(xiàn)數(shù)據(jù)索引切換即可:
完整源碼
獲取碎片數(shù)據(jù)代碼:
let shards = document.querySelectorAll('.shard')
const res = []
shards.forEach(ele => {
const allStyles = window.getComputedStyle(ele)
res.push({
clipPath: allStyles.getPropertyValue('clip-path'),
backgroundColor: allStyles.getPropertyValue('background-color')
})
})
console.log(JSON.stringify(res))
<template>
<Button @click="changeAnimal">切換</Button>
<div class="animal-container">
<template v-for="(item, index) in currentData" :key="index">
<div
class="clip-item"
:style="{
backgroundColor: item.backgroundColor,
clipPath: item.clipPath,
transitionDelay: `${index * 15}ms`,
}"
></div>
</template>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { Button } from 'ant-design-vue';
import data from './data.json';
const currentIndex = ref(0);
const currentData = ref(data[0]);
const length = data.length;
const changeAnimal = () => {
currentIndex.value++;
// 索引到最后了,重置為 0
if (currentIndex.value >= length) {
currentIndex.value = 0;
}
currentData.value = data[currentIndex.value];
};
</script>
<style scoped lang="less">
.animal-container {
width: 800px;
height: 600px;
position: relative;
.clip-item {
position: absolute;
width: 100%;
height: 100%;
// 動(dòng)畫過渡效果
transition-property: all;
transition-duration: 1000ms;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}
}
</style>