Guest User

Untitled

a guest
Dec 11th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <body>
  5. <canvas id="canvas" width="800" height="800"></canvas>
  6.  
  7. <p>
  8. Position of three stars might appear at corner, Please refresh the page.
  9. By Sihe Chen
  10. </p>
  11.  
  12. <script>
  13. window.onload = function () {
  14. var canvas = document.getElementById('canvas');
  15. var context = canvas.getContext('2d');
  16. var stars = [];
  17. var numberofstar = 3;
  18.  
  19. for(var star, i=0; i < numberofstar; i++){
  20. star = new Ball(20);
  21. star.x = Math.random() * canvas.width;
  22. star.y = Math.random() * canvas.height;
  23. star.mass = Math.floor(Math.random() * 10);
  24. stars.push(star);
  25. }
  26.  
  27. function G (a, b) {
  28. var dx = b.x - a.x;
  29. var dy = b.y - a.y;
  30. var rsqrt = Math.sqrt(dx * dx + dy * dy);
  31. var f = (a.mass * b.mass) / rsqrt;
  32. var accx = f * dx / rsqrt;
  33. var accy = f * dy / rsqrt;
  34. a.vx += accx / a.mass;
  35. b.vx -= accx / b.mass;
  36. a.vy += accy / a.mass;
  37. b.vy -= accy / b.mass;
  38. }
  39.  
  40. function movement(a, i){
  41. a.x += a.vx;
  42. a.y += a.vy;
  43.  
  44. for(var b, j = i + 1; j < numberofstar; j++){
  45. b = stars[j];
  46. G(a, b);
  47. }
  48. }
  49.  
  50. function draw(star){
  51. star.draw(context);
  52. }
  53.  
  54. (function drawFrame () {
  55. window.requestAnimationFrame(drawFrame, canvas);
  56. context.clearRect(0, 0, canvas.width, canvas.height);
  57. stars.forEach(movement);
  58. stars.forEach(draw);
  59. }());
  60. };
  61. </script>
  62. </body>
  63. </html>
  64.  
  65. <style type="text/css">
  66. #canvas {
  67. background-color: #e60000;
  68. border: 10px solid;
  69. }
  70. </style>
  71. <script>
  72. function Ball (radius) {
  73. this.x = 0;
  74. this.y = 0;
  75. this.radius = radius;
  76. this.vx = 0;
  77. this.vy = 0;
  78. this.mass = Math.floor(Math.random() * 10);
  79. }
  80. Ball.prototype.draw = function (context) {
  81. context.save();
  82. context.translate(this.x, this.y);
  83. context.beginPath();
  84. context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
  85. context.closePath();
  86. context.fill();
  87. context.restore();
  88. };
  89.  
  90. </script>
Add Comment
Please, Sign In to add comment