Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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.

Behavior

Auto Save

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.

HTML

              
                <div id="canvaswrapper">
    <em>Click on the canvas to stop/restart the animation</em>
    <canvas id="democanvas" width="960" height="600">
        HTML5 Canvas is not supported by your browser.
    </canvas>
</div>

<script type="text/javascript">
    window.onload = () => {
        const canvas = document.getElementById('democanvas'),
            canvasBounds = {'left': 0, 'right': canvas.width,
                'top': 0, 'bottom': canvas.height};

        const ctx = canvas.getContext('2d');

        const numberOfBalls = 150,
            ballRadius = 15,
            minVelocity = 3,
            maxVelocity = 5,
            colors = ['#FF0000', '#00FF00', '#0000FF',
                '#FFFF00', '#FF00FF', '#00FFFF'];

        // Create the "World" and populate it with Balls
        let world = new World(new Bounds(canvasBounds));
        for(let i=0; i < numberOfBalls; i++) {
            world.addObject(new Ball(ballRadius, colors[i % colors.length])
                .setRandomPosition(canvasBounds)
                .setRandomVelocity(minVelocity, maxVelocity));
        }

        let useWorker = false,
            worker = undefined;

        if ( useWorker ) {
            let workerThreadUrl = 'collider-worker.js';  // 'KopOrq.js';
            worker = new Worker(workerThreadUrl);

            // Wait for message back from worker thread with updated World object
            worker.addEventListener("message", (evt) => {
                if ( evt.data.message === "draw") {
                    world = World.restoreFromData(evt.data.world);
                    world.draw(ctx);
                    if (runAnimation) {
                        requestAnimationFrame(animationStep);
                    }
                }
            });
        }

        // The animation loop
        let runAnimation = true;
        function animationStep() {
            if (useWorker) {
                 worker.postMessage(world);  //do world.move() in worker
            } else {
                 world.move();
                 world.draw(ctx);
                 if (runAnimation) {
                     requestAnimationFrame(animationStep);
                 }
             }
        }
        animationStep();

        // Click/tap in canvas to stop/restart animation
        canvas.addEventListener("click", (evt) => {
            runAnimation = ! runAnimation;
            if (runAnimation) {
                animationStep();
            }
        });
    };
</script>

              
            
!

CSS

              
                body {
    background-color: #afd9ee;
}
#canvaswrapper {
    margin-left: auto;
    margin-right: auto;
    margin-top: 40px;
    width: 960px;
    height: 600px;
}
#democanvas {
    border: 2px solid #555;
    background-color: #3a87ad;
}

@media screen and (max-width: 800px) {
    #canvaswrapper {
        margin-left: auto;
        margin-right: auto;
        width: 600px;
        height: 600px;
    }
}

@media screen and (max-width: 400px) {
    #canvaswrapper {
        margin-left: 10px;
        margin-top: 20px;
        width: 300px;
        height: 300px;
    }
}

              
            
!

JS

              
                'use strict';
/*jshint esversion: 6 */
/* global exports */
/* global console */

/**
 * Collider: simple demo of collision physics.
 * Bruce Wilson, 1/29/2018
 */
class World {
    constructor(bounds) {
        this.bounds = bounds;
        this.animationStep = 0;
        this.displayList = [];
        this.moveDuration = 0;
        this.drawDuration = 0;

        this.options = {};
        // Clear before drawing: if not, an interesting canvas-filling
        // graphic is created
        this.options.clearBeforeDraw = true;
    }
    static restoreFromData(data) {
        // Restore from data that has been serialized to a worker thread
        const bounds = Bounds.restoreFromData(data.bounds),
            world = new World(bounds);
        world.animationStep = data.animationStep;
        world.displayList = [];
        world.moveDuration = data.moveDuration;
        world.options = data.options;
        data.displayList.forEach((obj) => {
            const ball = Ball.restoreFromData(obj);
            world.displayList.push(ball);
        });
        return world;
    }
    addObject(obj) {  // fluent
        this.displayList.push(obj);
        obj.id = this.displayList.length;
        return this;  // fluent
    }
    draw(ctx) {    // fluent, graphics
        const tstart = new Date().getTime(),
            drawingAreaBounds = this.bounds.getBounds();

        if (this.options.clearBeforeDraw) {
            ctx.clearRect(drawingAreaBounds.left, drawingAreaBounds.top,
                drawingAreaBounds.right, drawingAreaBounds.bottom);
        }
        this.displayList.forEach((obj) => {
            obj.draw(ctx);
        });

        const duration = (new Date().getTime() - tstart);
        if (duration > 0) {
            this.drawDuration = duration;
        }

        this.drawDurationText(ctx);

        return this;  // fluent
    }
    drawDurationText(ctx) {  // debugging
        const x = 10, y = 20;
        ctx.font = '16px sans-serif';
        ctx.fillStyle = '#e0e0e0';
        ctx.fillText("Move: " + this.moveDuration + " msec, Draw: " +
            this.drawDuration + " msec", x, y);
    }
    move() {  // fluent
        this.animationStep += 1;

        const tstart = new Date().getTime();
        this.checkForCollisions();
        const duration = (new Date().getTime() - tstart);
        if ( duration > 1) {
            // 60 fps => 16.7 msec per frame
            // console.log('%d Check for collisions: %d msec', this.animationStep, duration);
            this.moveDuration = duration;
        }

        let self = this;
        this.displayList.forEach((obj) => {
            self.bounds.checkInBounds(obj);
        });

        this.displayList.forEach((obj) => {
            obj.move();
        });
        return this;  // fluent
    }
    checkForCollisions() {
        const listLength = this.displayList.length;
        for (let i=0; i < listLength; i++) {
            const obj1 = this.displayList[i];
            for (let j=i + 1; j < listLength; j++) {
                const obj2 = this.displayList[j],
                    minDist = obj1.getRadius() + obj2.getRadius(),
                    dist = obj1.distanceTo(obj2);

                // Check distance > 0 for degenerate case where balls overshoot
                if ( dist > 0 && dist < minDist ) {
                    // console.log("Collision: i=%d, j=%d, dist=%.3f, minDist=%.3f", i, j, dist, minDist);
                    // This reverses the direction of movement of each object
                    const newVelocity1 = obj1.bounceOff(obj2),
                        newVelocity2 = Vector.negate(newVelocity1);
                    // console.log("vel1: " + JSON.stringify(newVelocity1)); // debugging
                    // console.log("vel2: " + JSON.stringify(newVelocity2));
                    this.separateOverlappedBalls(obj1, obj2);
                    obj1.setVelocity(newVelocity1);
                    obj2.setVelocity(newVelocity2);
                }
            }
        }
    }
    // TODO: try an alternate "separate" method that checks dot products
    separateOverlappedBalls(ball1, ball2) {
        const vdiff = Vector.subtract(ball2.getPosition(), ball1.getPosition()),
            radiusSum = ball1.getRadius() + ball2.getRadius(),
            dist = ball1.distanceTo(ball2),
            pos1 = ball1.getPosition(),
            pos2 = ball2.getPosition();

        // Adjust each ball's position by half the difference
        // of the sum of the radii and the distance
        const adjustDist = radiusSum - dist,
            adjust = Vector.divide(Vector.setMagnitude(vdiff, adjustDist), 2.0);
        ball1.setPosition({x: pos1.x + adjust.x, y: pos1.y + adjust.y});
        ball2.setPosition({x: pos2.x - adjust.x, y: pos2.y - adjust.y});
    }
    ballsOverlap(ball1, ball2, dist) {
        return dist < ball1.getRadius() + ball2.getRadius();
        // return dist < Math.min(obj1.getRadius(), obj2.getRadius());
    }
}

class Bounds {
    constructor(bounds) {
        this.bounds = { top: bounds.top, right: bounds.right,
            bottom: bounds.bottom, left: bounds.left };
    }
    static restoreFromData(data) {
        return new Bounds(data.bounds);
    }
    getBounds() { return this.bounds; }
    checkInBounds(obj) {
        const objBounds = obj.getBounds();

        // Bounce if crossing a boundary
        if ( objBounds.left < this.bounds.left ) {
            obj.velocity.x = - obj.velocity.x;
            // Make sure ball is within bounds: counteract overshoot
            obj.position.x = this.bounds.left + obj.radius;
        }
        if ( objBounds.right > this.bounds.right ) {
            obj.velocity.x = - obj.velocity.x;
            obj.position.x = this.bounds.right - obj.radius;
        }
        if ( objBounds.top < this.bounds.top ) {
            obj.velocity.y = - obj.velocity.y;
            obj.position.y = this.bounds.top + obj.radius;
        }
        if ( objBounds.bottom > this.bounds.bottom ) {
            obj.velocity.y = - obj.velocity.y;
            obj.position.y = this.bounds.bottom - obj.radius;
        }
    }
}

class CircularBounds {
    constructor(bounds) {
        this.bounds = { top: bounds.top, right: bounds.right,
            bottom: bounds.bottom, left: bounds.left };
        const width = bounds.right - bounds.left,
            height = bounds.bottom - bounds.top;
        this.center = {x: width / 2.0, y: height / 2.0};
        this.radius = Math.min(width / 2.0, height / 2.0);
    }
    static restoreFromData(data) {
        const bounds = new Bounds(data.bounds);
        bounds.radius = data.bounds.radius;
        return bounds;
    }
    getBounds() { return this.bounds; }
    checkInBounds(obj) {
        const objBounds = obj.getBounds();

        const vDistToCenter = Vector.subtract(obj.getPosition(), this.center),
            distToCenter = Vector.magnitude(vDistToCenter);

        if ( distToCenter + obj.getRadius() > this.radius) {
            // bounce off boundary
        }
    }
}

class Ball {
    constructor(radius, color, position={x: 0, y: 0}, velocity={x: 0, y: 0}) {
        this.id = 0;
        this.radius = radius;
        this.color = color;
        this.position = position;
        this.velocity = velocity;
    }
    static restoreFromData(data) {
        // Restore from data that's been serialized to a worker thread
        const ball = new Ball(data.radius, data.color);
        ball.position = data.position;
        ball.velocity = data.velocity;
        return ball;
    }
    getPosition() { return {x: this.position.x, y: this.position.y}; }
    setPosition(p) { this.position = {x: p.x, y: p.y}; return this; }  // fluent method
    getVelocity() { return {x: this.velocity.x, y: this.velocity.y}; }
    setVelocity(v) { this.velocity = {x: v.x, y: v.y};  return this; }  // fluent method
    getRadius() { return this.radius; }
    getBounds() {
        return {top:(this.position.y - this.radius), right:(this.position.x + this.radius),
            bottom:(this.position.y + this.radius), left:(this.position.x - this.radius)};
    }
    move() {
        // Move according to the current velocity
        this.position.x = this.position.x + this.velocity.x;
        this.position.y = this.position.y + this.velocity.y;
    }
    draw(ctx) {    // graphics
        const FULLCIRCLE = 2 * Math.PI;  // TODO
        ctx.beginPath();
        ctx.arc(this.position.x, this.position.y, this.radius, 0, FULLCIRCLE, true);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.strokeStyle = '#202020';
        ctx.strokeWeight = 0.25;
        ctx.stroke();
        // this.drawVelocity(ctx);  // debugging
    }
    drawVelocity(ctx) {  // for debugging
        const multiplier = 5;
        ctx.beginPath();
        ctx.moveTo(this.position.x, this.position.y);
        ctx.lineTo(this.position.x + multiplier * this.velocity.x,
            this.position.y + multiplier * this.velocity.y);
        ctx.strokeStyle = '#202020';
        ctx.strokeWeight = 2.0;
        ctx.stroke();
    }
    bounceOff(otherBall) {
        // There's no consideration of mass or conservation of momentum
        // in this simple example - each ball retains its velocity, it
        // just moves off in a different direction
        // console.log("bounce " + this + " off " + otherBall);
        const normalVector =
                Vector.unitVector(Vector.subtract(otherBall.getPosition(), this.getPosition())),  // TODO
            incidentVector = Vector.unitVector(this.getVelocity()),
            scalarSpeed = Vector.magnitude(this.getVelocity()),
            ndotI = - 2.0 * Vector.dotProduct(normalVector, incidentVector);
        let newVelocity = Vector.multiply(normalVector, ndotI);

        newVelocity = Vector.subtract(incidentVector, newVelocity);
        newVelocity = Vector.setMagnitude(newVelocity, scalarSpeed);
        return newVelocity;
    }
    distanceTo(otherBall) {
        const pos1 = this.getPosition(),
            pos2 = otherBall.getPosition(),
            dx = pos1.x - pos2.x,
            dy = pos1.y - pos2.y;
        return Math.sqrt(dx * dx + dy * dy);
    }
    setRandomPosition(bounds) {  // fluent method
        const x = Math.random() * (bounds.right - bounds.left) + bounds.left,
            y = Math.random() * (bounds.bottom - bounds.top) + bounds.top;
        this.position = {x: x, y: y};
        return this;  // fluent method
    }
    setRandomVelocity(minVelocity = 2, maxVelocity=5) {  // fluent method
        const velocityRange = Math.abs(maxVelocity - minVelocity);
        let direction = (Math.random() > 0.5) ? 1 : -1;
        this.velocity.x = direction * (velocityRange * Math.random() + minVelocity);
        direction = (Math.random() > 0.5) ? 1 : -1;
        this.velocity.y = direction * (velocityRange * Math.random() + minVelocity);
        return this;  // fluent method
    }
    toString() {
        const id = this.id || 0,
            precision = 1,
            xpos = (this.position.x).toFixed(precision),
            ypos = (this.position.y).toFixed(precision),
            vx = (this.velocity.x).toFixed(precision),
            vy = (this.velocity.y).toFixed(precision);
        return id + ", pos: (" + xpos + ", " + ypos + "), vel: (" + vx + ", " + vy + ")";
    }
}

window.Vector = (function(){
    "use strict";

    return {
        // Operates on vectors as object literals like '{x: ..., y: ...}'
        dotProduct: function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); },
        magnitude: function(v1) { return Math.sqrt((v1.x * v1.x) + (v1.y * v1.y)); },
        unitVector: function(v1) {
            const magn = Vector.magnitude(v1);
            return {x: v1.x / magn, y: v1.y / magn};
        },
        setMagnitude: function(v1, m) {
            // Assuming uv is a unit vector, the x and y components of uv
            // are the cosine and sine of the vectors
            let magn = Vector.magnitude(v1);
            return {x: m * v1.x / magn, y: m * v1.y / magn};
        },
        subtract: function(v1, v2) {
            // Subtract v2 - v1, gives a vector from v2 to v1
            return {x: (v2.x - v1.x), y: (v2.y - v1.y)};
        },
        negate: function(v) { return {x: -v.x, y: -v.y}; },
        multiply: function(v1, scalarValue) { return {x: (v1.x * scalarValue), y: (v1.y * scalarValue)}; },
        divide: function(v1, scalarValue) { return {x: (v1.x / scalarValue), y: (v1.y / scalarValue)}; },
        same: function(v1, v2, tolerance=0.00001) {
            return (Math.abs(v1.x - v2.x) < tolerance) && (Math.abs(v1.y - v2.y) < tolerance);
        },
        asString: function(v) { return "{x: " + v.x + ", y:" + v.y + "}"; }
    };
})();

if (typeof exports !== 'undefined') {
    exports.World = World;
    exports.Bounds = Bounds;
    exports.CircularBounds = CircularBounds;
    exports.Ball = Ball;
    exports.Vector = Vector;
}

              
            
!
999px

Console