广树
2024-11-21 16:04
@hikari:BGM也许是吧,歌曲部分感觉不一定
作者:广树时间:2018-02-02 16:19:02分类:JavaScript/jQuery/Vue
其实原理就是控制正弦波的幅度。
CSS:
html, body { height: 100%; text-align: center; background-color: #323436; } canvas#sineCanvas { width:500px; height:500px; overflow:hidden; background:#5b5d5e; }
HTML:
<div id="canvas-container"> <canvas id="sineCanvas"></canvas> </div>
JS:
(function () { var unit = 100, canvas, context, canvas2, context2, height, width, xAxis, yAxis, draw; var percentMax = 0.6;//液体占容器的百分比 var percentMin = 0; var maxHeight = 1; if(percentMax>=1){ maxHeight = 0.95; } var wavePower = 3; //初始化 function init() { window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000/60); }; })(); canvas = document.getElementById("sineCanvas"); canvas.width = 1000; canvas.height = 1000; context = canvas.getContext("2d"); height = canvas.height; width = canvas.width; yAxis = 0; draw(); } function draw() { // 清理canvas画板 context.clearRect(0, 0, width, height); //描绘波浪 drawWave(['#cea155','#e8c183'], 1, 1.5); if(percentMin<=percentMax){ percentMin = percentMin+0.002; xAxis = Math.floor(height*(maxHeight-percentMin)); } if(percentMin>0.80){ if(wavePower<=36*percentMax){ wavePower = wavePower+0.05 } } // 更新时间然后重新绘制 draw.seconds = draw.seconds + .009; draw.t = draw.seconds*Math.PI; window.requestAnimFrame(draw); }; draw.seconds = 0; draw.t = 0; /** * 描绘波浪 * drawWave([渐变左侧颜色,右侧颜色], 不透明度, 波浪的幅度) */ function drawWave(color, alpha, zoom) { context.globalAlpha = alpha; var linearGrad = context.createLinearGradient(0, 0, width, 0); linearGrad.addColorStop(0.0, color[0]); linearGrad.addColorStop(1.0, color[1]); context.fillStyle = linearGrad; context.beginPath(); //开始路径 drawSine(draw.t / 0.5, zoom); context.lineTo(width + 10, height); //路径朝canvas右下 context.lineTo(0, height); //路径朝canvas左下 context.closePath() //封闭路径 context.fill(); //涂色 } /** * 画正弦 * drawSine(时间, 波浪的浮动) */ function drawSine(t, zoom) { var x = t; //将时间转换为x轴 var y = Math.sin(x)/zoom; context.moveTo(yAxis, unit*y+xAxis); //在开始位置放置路径 // 绘制波浪、横向幅度 for (var i = yAxis; i <= width + 10; i += 10) { x = t+(-yAxis+i)/unit/zoom; y = Math.sin(x - 0)/wavePower; context.lineTo(i, unit*y+xAxis); } } init(); })();