效果如下(渣渣截图软件):

三、绘制完整填充路径
以上路径虽有闭合,但却不满足我们需要填充的部分,直接填充效果如下:

完整填充路径应如图所示:

闭合路径后创建一个渐变颜色,作为填充颜色,代码如下:
| var lingrad = ctx.createLinearGradient(0,0,width,0); lingrad.addColorStop(0, 'rgba(0,186,128,0.8)'); lingrad.addColorStop(1, 'rgba(111,224,195,1)'); (function draw(){ window.requestAnimationFrame(draw); ctx.clearRect(0, 0, width, height); ctx.beginPath(); ctx.strokeStyle="#000"; ctx.fillStyle = lingrad; ctx.lineWidth = 1; ctx.moveTo(0, height /2); Q+=speed; for (let x = 0; x <= width; x++) { var y = A*Math.sin(W*x+Q) +H; ctx.lineTo(x, y); } ctx.lineTo(width, height); ctx.lineTo(0, height); ctx.fill(); ctx.closePath(); })() |
效果如下:

四、完善水波动画
1、首先可以对上面波形叠加一个频率更高的波形,使波形无规矩
| var s = 0.1*Math.sin(x/150)+1; var y = A*Math.sin(W*x+Q) +H; y=y*s; |
2、再添加一个相位变化不同的波形,其渐变填充与上一个渐变方向相反使其形成相互重叠的阴影效果;并设置路径重叠效果globalCompositeOperation;
| var canvas = document.getElementById("canvas"), ctx = canvas.getContext('2d'), width = canvas.width = canvas.offsetWidth, height = canvas.height = canvas.offsetHeight; var A=30, W=1 /200, Q=0, H= height / 2; var A2=30, W2=1/300, Q2=0, H2= height / 2; var speed=-0.01; var speed2=-0.02; var lingrad = ctx.createLinearGradient(0,0,width,0); lingrad.addColorStop(0, 'rgba(0,186,128,0.8)'); lingrad.addColorStop(1, 'rgba(111,224,195,1)'); var lingrad2 = ctx.createLinearGradient(0,0,width,0); lingrad2.addColorStop(0,'rgba(111,224,195,1)'); lingrad2.addColorStop(1, 'rgba(0,186,128,0.8)'); (function draw(){ window.requestAnimationFrame(draw); ctx.clearRect(0, 0, width, height); ctx.beginPath(); ctx.fillStyle = lingrad; ctx.moveTo(0, height /2); //绘制第一个波形 Q+=speed; for (let x = 0; x <= width; x++) { var s = 0.1*Math.sin(x/150)+1; var y = A*Math.sin(W*x+Q) +H; y=y*s; ctx.lineTo(x, y); } ctx.lineTo(width, height); ctx.lineTo(0, height); ctx.fill(); ctx.closePath() //设置重叠效果 ctx.globalCompositeOperation = "destination-over" //绘制第二个波形 ctx.beginPath(); ctx.fillStyle = lingrad2; Q2+=speed2; for (let x = 0; x < width; x++) { var y = A2*Math.sin(x*W2+Q2) +H2; ctx.lineTo(x, y); } ctx.lineTo(width,height); ctx.lineTo(0,height); ctx.fill() ctx.closePath(); })() |









