1
0

spectrum.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * 频谱动画模拟
  3. * */
  4. var canvas, ctx,
  5. specItems = [],
  6. needStop = false,
  7. timer = null,
  8. random = Math.random;
  9. function randHeight() {
  10. if (random() > 0.8) {
  11. return random() * 8 + 11;
  12. } else {
  13. return random() * 6 + 2;
  14. }
  15. }
  16. var randHeightGenerator = function (base) {
  17. var max = base * 1.5 > 28 ? 28 : base * 1.5,
  18. min = 1,
  19. direction = random() > 0.5 ? 1 : -1,
  20. tempHeight = base,
  21. curStep;
  22. return function () {
  23. curStep = direction;
  24. tempHeight += curStep;
  25. if (tempHeight >= max) {
  26. direction *= -1;
  27. tempHeight = max;
  28. } else if (tempHeight <= min) {
  29. direction *= -1;
  30. tempHeight = min;
  31. }
  32. if (random() > 0.9) {
  33. direction *= -1;
  34. }
  35. return tempHeight;
  36. }
  37. };
  38. function loop() {
  39. ctx.clearRect(0, -canvas.height / 2, canvas.width, canvas.height);
  40. for (var i = 0; i < specItems.length; i++) {
  41. var item = specItems[i];
  42. var height = item.getHeight();
  43. ctx.fillRect(i + specItems[i].xSpace, -height / 2, specItems[i].width, height);
  44. }
  45. if (!needStop) {
  46. timer = requestAnimationFrame(loop);
  47. }
  48. }
  49. function init(canvasElem, width = 220, height = 30, color = '#D94240') {
  50. canvas = canvasElem;
  51. canvas.width = width;
  52. canvas.height = height;
  53. ctx = canvas.getContext('2d');
  54. ctx.fillStyle = color;
  55. ctx.translate(0, height / 2);
  56. for (let i = 0; i < 64; i++) {
  57. var xSpace = i == 0 ? 0 : 5 * i;
  58. var tempItem = {
  59. xSpace : xSpace,
  60. width : 1,
  61. getHeight: randHeightGenerator(randHeight())
  62. };
  63. specItems.push(tempItem);
  64. }
  65. }
  66. function draw() {
  67. needStop = false;
  68. loop();
  69. }
  70. function stop() {
  71. needStop = true;
  72. }
  73. export {init, draw, stop};