Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <body>
- <canvas id="canvas" width="800" height="800"></canvas>
- <p>
- Position of three stars might appear at corner, Please refresh the page.
- By Sihe Chen
- </p>
- <script>
- window.onload = function () {
- var canvas = document.getElementById('canvas');
- var context = canvas.getContext('2d');
- var stars = [];
- var numberofstar = 3;
- for(var star, i=0; i < numberofstar; i++){
- star = new Ball(20);
- star.x = Math.random() * canvas.width;
- star.y = Math.random() * canvas.height;
- star.mass = Math.floor(Math.random() * 10);
- stars.push(star);
- }
- function G (a, b) {
- var dx = b.x - a.x;
- var dy = b.y - a.y;
- var rsqrt = Math.sqrt(dx * dx + dy * dy);
- var f = (a.mass * b.mass) / rsqrt;
- var accx = f * dx / rsqrt;
- var accy = f * dy / rsqrt;
- a.vx += accx / a.mass;
- b.vx -= accx / b.mass;
- a.vy += accy / a.mass;
- b.vy -= accy / b.mass;
- }
- function movement(a, i){
- a.x += a.vx;
- a.y += a.vy;
- for(var b, j = i + 1; j < numberofstar; j++){
- b = stars[j];
- G(a, b);
- }
- }
- function draw(star){
- star.draw(context);
- }
- (function drawFrame () {
- window.requestAnimationFrame(drawFrame, canvas);
- context.clearRect(0, 0, canvas.width, canvas.height);
- stars.forEach(movement);
- stars.forEach(draw);
- }());
- };
- </script>
- </body>
- </html>
- <style type="text/css">
- #canvas {
- background-color: #e60000;
- border: 10px solid;
- }
- </style>
- <script>
- function Ball (radius) {
- this.x = 0;
- this.y = 0;
- this.radius = radius;
- this.vx = 0;
- this.vy = 0;
- this.mass = Math.floor(Math.random() * 10);
- }
- Ball.prototype.draw = function (context) {
- context.save();
- context.translate(this.x, this.y);
- context.beginPath();
- context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
- context.closePath();
- context.fill();
- context.restore();
- };
- </script>
Add Comment
Please, Sign In to add comment