tongji.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. (function () {
  2. 'use strict';
  3. var c = document.getElementById('c');
  4. var ctx = c.getContext('2d');
  5. var w = c.width = window.innerWidth;
  6. var h = c.height = window.innerHeight;
  7. var cx = w / 2;
  8. var cy = h / 2;
  9. var P = function (x, y) {
  10. this.x = x;
  11. this.y = y;
  12. this.vx = 0;
  13. this.vy = 0;
  14. this.r = 1 + Math.random() * 10;
  15. this.sa = Math.random() * Math.PI * 2;
  16. this.ea = Math.random() * Math.PI * 2;
  17. this.rt = Math.random() * Math.PI * 2;
  18. this.vrt = 0;
  19. this.h = 0;
  20. };
  21. P.prototype = {
  22. constructor: P,
  23. update: function () {
  24. this.vx += Math.random() * 0.1 - 0.05;
  25. this.vy += Math.random() * 0.1 - 0.05;
  26. this.vrt += Math.random() * 0.02 - 0.01;
  27. this.x += this.vx;
  28. this.y += this.vy;
  29. this.rt += this.vrt;
  30. var dx = cx - this.x;
  31. var dy = cy - this.y;
  32. var d = Math.sqrt(dx * dx + dy * dy);
  33. this.h = dx / d * 360;
  34. if (this.x < 0) {
  35. this.x = 0;
  36. this.vx *= -1;
  37. }
  38. if (this.x > w) {
  39. this.x = w;
  40. this.vx *= -1;
  41. }
  42. if (this.y < 0) {
  43. this.y = 0;
  44. this.vy *= -1;
  45. }
  46. if (this.y > h) {
  47. this.y = h;
  48. this.vy *= -1;
  49. }
  50. },
  51. render: function (ctx) {
  52. ctx.save();
  53. ctx.strokeStyle = 'black';
  54. ctx.fillStyle = 'hsla(' + this.h + ', 100%, 50%, 0.5)';
  55. ctx.translate(this.x, this.y);
  56. ctx.rotate(this.rt);
  57. ctx.beginPath();
  58. ctx.arc(0, 0, this.r, this.sa, this.ea);
  59. ctx.fill();
  60. ctx.stroke();
  61. ctx.restore();
  62. }
  63. };
  64. var ps = [];
  65. var p;
  66. var ctr = 200;
  67. for (var i = 0; i < ctr; i++) {
  68. p = new P(Math.random() * w, Math.random() * h);
  69. ps.push(p);
  70. }
  71. requestAnimationFrame(function loop() {
  72. requestAnimationFrame(loop);
  73. ctx.clearRect(0, 0, w, h);
  74. for (var i = 0; i < ctr; i++) {
  75. p = ps[i];
  76. p.update();
  77. p.render(ctx);
  78. }
  79. for (var i = 0; i < ctr; i++) {
  80. var p1 = ps[i];
  81. for (var j = i + 1; j < ctr; j++) {
  82. var p2 = ps[j];
  83. var dx = p1.x - p2.x;
  84. var dy = p1.y - p2.y;
  85. var d = Math.sqrt(dx * dx + dy * dy);
  86. if (d < 50) {
  87. ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
  88. ctx.beginPath();
  89. ctx.moveTo(p1.x, p1.y);
  90. ctx.lineTo(p2.x, p2.y);
  91. ctx.stroke();
  92. }
  93. }
  94. }
  95. });
  96. })();