canvas 音乐跳动效果
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <style type="text/css"> * {margin: 0;padding: 0;} html, body {height: 100%;overflow: hidden;} .music-play {margin: 100px;} </style> </head> <body> <div class="music-play"> <canvas width="200" height="100"></canvas> </div> </body> <script type="text/javascript"> window.onload = function() { const oc = document.querySelector('canvas'); if (oc.getContext('2d')) { const ctx = oc.getContext('2d'); const lineArr = [ { start: { x: 40, }, end: { x: 40, y: 60 } }, { start: { x: 80 }, end: { x: 80, y: 80 } }, { start: { x: 120 }, end: { x: 120, y: 100 } }, { start: { x: 160 }, end: { x: 160, y: 120 } } ]; function step() { ctx.clearRect(0, 0, oc.width, oc.height); ctx.save(); ctx.fillStyle = "#000"; ctx.fillRect(0, 0, oc.width, oc.height); ctx.restore(); for (let i = 0; i < lineArr.length; i++) { if (lineArr[i].end.y >= oc.height - 30) { lineArr[i].end.dir = 'add'; } else if (lineArr[i].end.y <= 30) { lineArr[i].end.dir = 'minus'; } if (lineArr[i].end.dir === 'minus') { lineArr[i].end.y += 2; } else { lineArr[i].end.y -= 2; } } for (let i = 0; i < lineArr.length; i++) { ctx.save(); // ctx.beginPath(); // ctx.strokeStyle = 'yellow'; // ctx.moveTo(lineArr[i].start.x, oc.height); // ctx.lineTo(lineArr[i].end.x, oc.height - lineArr[i].end.y); ctx.fillStyle = "yellow"; ctx.fillRect(lineArr[i].start.x, oc.height - lineArr[i].end.y, 5, lineArr[i].end.y); // ctx.stroke(); ctx.restore(); } window.requestAnimationFrame(step); } window.requestAnimationFrame(step); } } </script> </html>
掌控自己,掌控命运