javascript画布
时间: 2023-09-09 13:07:16 浏览: 44
怎样实现波浪效果?
可以使用sin()和cos()函数来实现波浪效果,具体实现方式可以参考以下代码:
```javascript
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
let time = 0;
let animationId;
function draw() {
animationId = requestAnimationFrame(draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let x = 0; x <= canvas.width; x += 10) {
const y = canvas.height / 2 + Math.sin(x / 30 + time) * 50;
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fill();
}
time += 0.1;
}
draw();
```
这段代码实现了一个简单的波浪效果,每个波峰和波谷的 y 坐标都是根据 sin() 函数计算得出的。可以根据自己的需要调整函数参数和坐标值来实现不同的波浪效果。