canvas写一个渐变背景流动
时间: 2023-10-26 20:12:06 浏览: 44
以下是使用canvas创建渐变背景流动的示例代码:
```html
<canvas id="myCanvas"></canvas>
```
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 创建渐变
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(1, "green");
// 绘制矩形并填充渐变
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 定义位移量
let offset = 0;
// 每隔一定时间重绘图形
setInterval(() => {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 重新绘制矩形并填充渐变
ctx.fillStyle = gradient;
ctx.fillRect(offset, 0, canvas.width, canvas.height);
// 增加位移量
offset += 1;
// 如果超出画布宽度,重置位移量
if (offset > canvas.width) {
offset = 0;
}
}, 10);
```
这段代码首先在canvas上创建一个线性渐变,然后用该渐变填充整个矩形。接着,使用setInterval()函数每10毫秒重绘图形,并通过增加位移量来移动渐变的起点位置。如果位移量超出画布宽度,则将其重置为0,以实现循环流动的效果。