這是我參與更文挑戰的第20天,活動詳情查看:更文挑戰css
原理這裏就不介紹了,好長啊= =html
直接上代碼前端
寫一個canvas,並確保定位問題和寬高問題。vue
html
react
<template>
<div class="my-wrapper" v-cloak>
<!-- 頭部 -->
<div class="my-header row aCenter">
<!-- canvas背景 -->
<canvas id="canvas"></canvas>
</div>
</div>
</template>
複製代碼
css
ios
<style scoped>
.my-header{height: 230px;background-color: #6689e2;position: relative;}
#canvas {position: absolute; left: 0; right: 0; top: 0; width: 100%; height: 230px;}
</style>
複製代碼
<script lang="ts">
import { defineComponent, onMounted, nextTick } from 'vue'
export default defineComponent({
name: 'my',
props: {},
setup() {
// 建立canvas動畫
const oninitCanvas = () => {
nextTick(() => {
const canvas: any = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
height: number = canvas.offsetHeight,
width: number = canvas.offsetWidth,
lines: string[] = ["rgba(248, 248, 248, .4)", "rgba(248, 248, 248, .5)", "rgba(248, 248, 248, .6)"],
boHeight: number = height / 10,
posHeight: number = height / 1.8, // 波浪高度
canvasAny: any = { width: width, height: height },
requestAnimFrame = (function() { // 波浪自執行函數
return function(callback: any) {
setTimeout(callback, 100 / 6)
}
})()
let step: number = 0
// 動起來
const loop = function() {
ctx.clearRect(0, 0, canvasAny.width, canvasAny.height)
step++
// 畫三個不一樣顏色的矩陣
for(let j = lines.length - 1; j >= 0; j--) {
// 每一個矩陣的角度都不一樣,每一個之間相差100度
const angle: number = (step + j * 100) * Math.PI / 180,
deltaHeight: number = Math.sin(angle) * boHeight,
deltaHeightRight: number = Math.cos(angle) * boHeight
ctx.fillStyle = lines[j]
ctx.beginPath() // 開始繪製
ctx.moveTo(0, posHeight + deltaHeight)
ctx.bezierCurveTo(canvasAny.width / 2, posHeight + deltaHeight - boHeight, canvasAny.width / 2, posHeight + deltaHeightRight - boHeight, canvasAny.width, posHeight + deltaHeightRight)
ctx.lineTo(canvasAny.width, canvasAny.height)
ctx.lineTo(0, canvasAny.height)
ctx.lineTo(0, posHeight + deltaHeight)
ctx.fill() // 上色
ctx.closePath() // 結束繪製
}
requestAnimFrame(loop) // 啓動函數
}
// 隨機數
const random = function(min: number, max: number) {
return Math.floor(Math.random() * (max - min) + min)
}
loop()
})
}
onMounted(() => {
oninitCanvas()
})
}
})
</script>
複製代碼
這裏有幾個槽點:web
posHeight: number = height / 1.8
複製代碼
const angle: number = (step + j * 100) * Math.PI / 180
複製代碼
requestAnimFrame = (function() { // 波浪自執行函數
return function(callback: any) {
setTimeout(callback, 100 / 6)
}
})()
複製代碼
nextTick
函數下面去執行,否則會拿不到canvas
這個dom
對象的搞掂收工,有不懂的儘管問,我有空就會回覆的啦面試
大佬們,感興趣能夠關注我公衆號鴨,如今仍是個位數呢,委屈屈...vuex
人懶,不想配圖,望能幫到你們typescript
公衆號:
小何成長
,佛系更文,都是本身曾經踩過的坑或者是學到的東西有興趣的小夥伴歡迎關注我哦,我是:
何小玍。
你們一塊兒進步鴨