gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
使用html5 canvas写出海葵生长背景动画特效
- User
使用html5 canvas写出海葵生长背景动画特效
- Assistant
以下是使用HTML5 Canvas和JavaScript创建海葵生长背景动画特效:
HTML结构
<canvas id="canvas"></canvas>CSS样式
body { margin: 0; padding: 0; } canvas { background: #283548; display: block; }JavaScript代码
// 获取canvas标签和上下文对象 const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d') // 设置画布宽高 canvas.width = window.innerWidth canvas.height = window.innerHeight // 定义变量 const wave = { y: canvas.height / 2, length: 0.01, amplitude: 100, frequency: 0.02 } let increment = wave.frequency // 循环绘制 function animate() { requestAnimationFrame(animate) // 清空画布 ctx.fillStyle = 'rgba(0, 0, 0, 0.05)' ctx.fillRect(0, 0, canvas.width, canvas.height) // 绘制海葵 ctx.beginPath() ctx.moveTo(0, canvas.height / 2) for(let i = 0; i < canvas.width; i++) { ctx.lineTo(i, wave.y + Math.sin(i * wave.length + increment) * wave.amplitude * Math.sin(increment)) } ctx.strokeStyle = '#9AD5FF' ctx.stroke() increment += wave.frequency } animate()解析:
- 定义了一个wave对象,其中y属性为海葵的y坐标,length为波长,amplitude为振幅,frequency为频率。
- 利用Math.sin()函数生成正弦波。
- 利用Math.PI * 2生成一个有多个PI值的sin值,用于控制画布上海葵的摆动。
- 用requestAnimationFrame()方法来持续重绘动画,同时每次绘制前都要清空画布,利用ctx.fillRect()给canvas添加一层半透明蒙版。