其实原理就是控制正弦波的幅度。

CSS:

  1. html, body {
  2. height: 100%;
  3. text-align: center;
  4. background-color: #323436;
  5. }
  6.  
  7. canvas#sineCanvas {
  8. width:500px;
  9. height:500px;
  10. overflow:hidden;
  11. background:#5b5d5e;
  12. }

HTML:

  1. <div id="canvas-container">
  2. <canvas id="sineCanvas"></canvas>
  3. </div>

JS:

  1. (function () {
  2.  
  3. var unit = 100,
  4. canvas, context, canvas2, context2,
  5. height, width, xAxis, yAxis,
  6. draw;
  7. var percentMax = 0.6;//液体占容器的百分比
  8. var percentMin = 0;
  9. var maxHeight = 1;
  10. if(percentMax>=1){
  11. maxHeight = 0.95;
  12. }
  13. var wavePower = 3;
  14. //初始化
  15. function init() {
  16. window.requestAnimFrame = (function(){
  17. return window.requestAnimationFrame ||
  18. window.webkitRequestAnimationFrame ||
  19. window.mozRequestAnimationFrame ||
  20. function( callback ){
  21. window.setTimeout(callback, 1000/60);
  22. };
  23. })();
  24. canvas = document.getElementById("sineCanvas");
  25. canvas.width = 1000;
  26. canvas.height = 1000;
  27. context = canvas.getContext("2d");
  28. height = canvas.height;
  29. width = canvas.width;
  30. yAxis = 0;
  31. draw();
  32. }
  33. function draw() {
  34. // 清理canvas画板
  35. context.clearRect(0, 0, width, height);
  36.  
  37. //描绘波浪
  38. drawWave(['#cea155','#e8c183'], 1, 1.5);
  39. if(percentMin<=percentMax){
  40. percentMin = percentMin+0.002;
  41. xAxis = Math.floor(height*(maxHeight-percentMin));
  42. }
  43. if(percentMin>0.80){
  44. if(wavePower<=36*percentMax){
  45. wavePower = wavePower+0.05
  46. }
  47. }
  48. // 更新时间然后重新绘制
  49. draw.seconds = draw.seconds + .009;
  50. draw.t = draw.seconds*Math.PI;
  51. window.requestAnimFrame(draw);
  52. };
  53. draw.seconds = 0;
  54. draw.t = 0;
  55.  
  56. /**
  57. * 描绘波浪
  58. * drawWave([渐变左侧颜色,右侧颜色], 不透明度, 波浪的幅度)
  59. */
  60. function drawWave(color, alpha, zoom) {
  61. context.globalAlpha = alpha;
  62. var linearGrad = context.createLinearGradient(0, 0, width, 0);
  63. linearGrad.addColorStop(0.0, color[0]);
  64. linearGrad.addColorStop(1.0, color[1]);
  65. context.fillStyle = linearGrad;
  66. context.beginPath(); //开始路径
  67. drawSine(draw.t / 0.5, zoom);
  68. context.lineTo(width + 10, height); //路径朝canvas右下
  69. context.lineTo(0, height); //路径朝canvas左下
  70. context.closePath() //封闭路径
  71. context.fill(); //涂色
  72. }
  73.  
  74. /**
  75. * 画正弦
  76. * drawSine(时间, 波浪的浮动)
  77. */
  78. function drawSine(t, zoom) {
  79.  
  80. var x = t; //将时间转换为x轴
  81. var y = Math.sin(x)/zoom;
  82. context.moveTo(yAxis, unit*y+xAxis); //在开始位置放置路径
  83. // 绘制波浪、横向幅度
  84. for (var i = yAxis; i <= width + 10; i += 10) {
  85. x = t+(-yAxis+i)/unit/zoom;
  86. y = Math.sin(x - 0)/wavePower;
  87. context.lineTo(i, unit*y+xAxis);
  88. }
  89. }
  90.  
  91. init();
  92. })();