用VUE3.0写一个多颜色弥散渐变循环动态背景
时间: 2023-07-19 08:32:23 浏览: 251
好的,下面是代码实现:
```
<template>
<div class="gradient-bg">
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
mounted() {
this.initGradientBackground();
},
methods: {
initGradientBackground() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const colors = [
'#FFC107',
'#FF9800',
'#FF5722',
'#F44336',
'#E91E63',
'#9C27B0',
'#673AB7',
'#3F51B5',
'#2196F3',
'#03A9F4',
'#00BCD4',
'#009688',
'#4CAF50',
'#8BC34A',
'#CDDC39',
'#FFEB3B'
];
let index = 0;
function draw() {
const gradient = ctx.createLinearGradient(
0,
0,
canvas.width,
canvas.height
);
gradient.addColorStop(0, colors[index]);
gradient.addColorStop(1, colors[(index + 1) % colors.length]);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
index++;
if (index >= colors.length) {
index = 0;
}
requestAnimationFrame(draw);
}
draw();
}
}
};
</script>
<style scoped>
.gradient-bg {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
canvas {
display: block;
}
</style>
```
这段代码使用了 Canvas 来实现多颜色弥散渐变循环动态背景。具体实现思路是:每次循环取两种颜色,然后用 `createLinearGradient` 方法创建渐变,填充整个画布,以此来实现背景色的变化。同时,为了让背景色有渐变效果,我们使用 `requestAnimationFrame` 方法来不断重绘画布,从而实现动态效果。
阅读全文