Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Details

Privacy

Go PRO Window blinds lowered to protect code. Code Editor with window blinds (raised) and a light blub turned on.

Keep it secret; keep it safe.

Private Pens are hidden everywhere on CodePen, except to you. You can still share them and other people can see them, they just can't find them through searching or browsing.

Upgrade to PRO

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

Template

Make Template?

Templates are Pens that can be used to start other Pens quickly from the create menu. The new Pen will copy all the code and settings from the template and make a new Pen (that is not a fork). You can view all of your templates, or learn more in the documentation.

Template URL

Any Pen can act as a template (even if you don't flip the toggle above) with a special URL you can use yourself or share with others. Here's this Pen's template URL:

Screenshot

Screenshot or Custom Thumbnail

Screenshots of Pens are shown in mobile browsers, RSS feeds, to users who chose images instead of iframes, and in social media sharing.

This Pen is using the default Screenshot, generated by CodePen. Upgrade to PRO to upload your own thumbnail that will be displayed on previews of this pen throughout the site and when sharing to social media.

Upgrade to PRO

HTML

              
                <div>
	total speed:<input type="text" id="speedField" readonly>
    <input type="range" id="canvas-width" min="100" max="1000" step="1" value="250">
    <input type="range" id="canvas-height" min="100" max="1000" step="1" value="250">
    <canvas width="250" height="250"></canvas>
</div>

              
            
!

CSS

              
                html, body {
  background-color: #6495ED;
}

div {
  position: absolute;
  left: 50px;
  top: 50px;
}

canvas, input {
  display: block;
}

              
            
!

JS

              
                const numBalls = 10;
const minRadius = 10;
const maxRadius = 10;
const initialVelocity = 3;

var canvas;
var context;
var balls;

var speedField;

window.addEventListener('load', app);

function app() {
  canvas = document.querySelector('canvas');
  context = canvas.getContext('2d');

  speedField = document.getElementById('speedField');

  document.getElementById('canvas-width').addEventListener('input', evt => {
    canvas.width = evt.target.value;
  });

  document.getElementById('canvas-height').addEventListener('input', evt => {
    canvas.height = evt.target.value; 
  });

  generateBalls();

  window.requestAnimationFrame(draw);

}

function generateBalls() {
  function polarToComponent(magnitude, angle) {
    return {
      x: magnitude * Math.cos(angle),
      y: magnitude * Math.sin(angle)
    };
  }

  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function getRandom(min, max) {
    return Math.random() * (max - min) + min;
  }

  balls = [];

  for (let n = 0; n < numBalls; n += 1) {
    let radius = getRandomInt(minRadius, maxRadius);
    let ball = {
      radius: radius,
      get mass() { return this.radius; }, // trivial: ball mass equals ball size
      center: {
        x: getRandomInt(0, canvas.width),
        y: getRandomInt(0, canvas.height)
      },
      nextCenter: {},
      velocity: polarToComponent(initialVelocity, getRandom(0, 2 * Math.PI)),
      color: `rgb(${getRandomInt(0, 128)},${getRandomInt(0, 128)},${getRandomInt(0, 128)})`
    };

    balls.push(ball);
  }        
}

function draw() {
  updatePositions();

  bounceWalls();

  checkCollisions();

  render();

  window.requestAnimationFrame(draw);
}

function updatePositions() {
  balls.forEach(ball => {
    ball.nextCenter.x = ball.center.x + ball.velocity.x;
    ball.nextCenter.y = ball.center.y + ball.velocity.y;
  });
}

function bounceWalls() {
  balls.forEach(ball => {
    let leftEdge = ball.nextCenter.x - ball.radius;
    let rightEdge = ball.nextCenter.x + ball.radius;
    let topEdge = ball.nextCenter.y - ball.radius;
    let bottomEdge = ball.nextCenter.y + ball.radius;

    if (leftEdge <= 0) {
      ball.velocity.x = -ball.velocity.x;
      ball.nextCenter.x = ball.radius;
    } else if (rightEdge >= canvas.width) {
      ball.velocity.x = -ball.velocity.x;
      ball.nextCenter.x = canvas.width - ball.radius;
    }

    if (topEdge <= 0) {
      ball.velocity.y = -ball.velocity.y;
      ball.nextCenter.y = ball.radius;
    } else if (bottomEdge >= canvas.height) {
      ball.velocity.y = -ball.velocity.y;
      ball.nextCenter.y = canvas.height - ball.radius;
    }
  });
}

// https://en.wikipedia.org/wiki/Elastic_collision#Two-dimensional_collision_with_two_moving_objects
function checkCollisions() {

  for (let i = 0; i < balls.length; i += 1) {

    let ballOne = balls[i];

    for (let j = i + 1; j < balls.length; j += 1) {

      let ballTwo = balls[j];

      // direction vector (x1-x2)
      let direction = { 
        x: ballOne.center.x - ballTwo.center.x,
        y: ballOne.center.y - ballTwo.center.y
      };

      // absolute distance between balls
      // ||x1-x2||^2
      let absDistanceSquared = direction.x * direction.x + direction.y * direction.y;

      // minimum distance between balls before they are overlapping; use squares
      // to save two unnecessary square root calculations)
      // (r1+r2)^2 
      let minDistanceSquared = (ballOne.radius + ballTwo.radius) * (ballOne.radius + ballTwo.radius);

      // two balls collide when they are less than r1+r2 distance apart
      // ||x1-x2||^2 <= (r1+r2)^2
      if (absDistanceSquared <= minDistanceSquared) {

        // velocity vector (v2-v1)
        let velocity = { 
          x: ballTwo.velocity.x - ballOne.velocity.x,
          y: ballTwo.velocity.y - ballOne.velocity.y
        };

        // dot product <v2-v1,x1-x2>
        let dotProduct = velocity.x * direction.x + velocity.y * direction.y;

        // 1. if dot product of two vectors is negative, then the angle between the vectors is greater 
        //    than 90 degrees;
        // 
        // 2. if the velocity vector is pointing away from the direction of the collision, then the 
        //    balls are moving away from each other;
        //
        // 3. if the balls are moving away from each other, then they are not colliding.
        //
        if (dotProduct <= 0) {
          continue;
        }

        // m1+m2
        let totalMass = ballOne.mass + ballTwo.mass;

        //   2 * m2
        // ----------
        //   (m1+m2)
        let massFactorOne = 2 * ballTwo.mass / totalMass;

        //   2 * m1
        // ----------
        //   (m1+m2)
        let massFactorTwo = 2 * ballOne.mass / totalMass;

        //  <v2-v1,x1-x2>
        // ---------------
        //   ||x1-x2||^2
        let scaledMomentum = dotProduct / absDistanceSquared;

        // combined scalar values:
        //
        //   2 * m2      <v1-v2,x1-x2>            2 * m1      <v1-v2,x1-x2>
        // ---------- * ---------------   and   ---------- * ---------------
        //   (m1+m2)      ||x1-x2||^2             (m1+m2)      ||x1-x2||^2
        let scalarOne = massFactorOne * scaledMomentum;
        let scalarTwo = massFactorTwo * scaledMomentum;

        ballOne.velocity.x = ballOne.velocity.x + (scalarOne * direction.x);
        ballOne.velocity.y = ballOne.velocity.y + (scalarTwo * direction.y);
        ballTwo.velocity.x = ballTwo.velocity.x - (scalarOne * direction.x);
        ballTwo.velocity.y = ballTwo.velocity.y - (scalarTwo * direction.y);
      }
    }
  }
}

function render() {
  var v = 0;

  context.fillStyle = '#eeeeee';
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.strokeStyle = '#000000';
  context.strokeRect(1, 1, canvas.width-2, canvas.height-2);

  balls.forEach(ball => {

    v += Math.sqrt(ball.velocity.x * ball.velocity.x + ball.velocity.y * ball.velocity.y);
    ball.center.x = ball.nextCenter.x;
    ball.center.y = ball.nextCenter.y;
    context.fillStyle = ball.color;
    context.beginPath();
    context.arc(ball.center.x, ball.center.y, ball.radius, 0, 2 * Math.PI, true);
    context.closePath();
    context.fill();
  });

  speedField.value = v;
}

              
            
!
999px
How would you React if I said I love Vue?

Console