JSFiddle - React, Tailwind, and code Playground

by Thiago Figueiredo

HTML

<script src="http://wellcaffeinated.net/PhysicsJS/examples/physicsjs-full.js"></script>
<canvas id="viewport" width="500" height="400"></canvas>

CSS

#viewport {
        border: solid 1px #000;
    }

JavaScript

// create a behavior to handle pin constraints
Physics.behavior('pin-constraints', function( parent ){
    return {
        init: function( opts ){
            parent.init.call( this, opts );
            this.pins = [];
        },
        
        add: function( body, targetPos ){
            this.pins.push({
                body: body,
                target: Physics.vector( targetPos )
            });
        },
        
        behave: function( data ){
            
            var pins = this.pins
                ,pin
                ;
            
            for (var i = 0, l = pins.length; i < l; i++){
                pin = pins[ i ];
                // move body to correct position
                pin.body.state.pos.clone( pin.target );
            }
        }
    };
});

Physics(function (world) {
    var renderer = Physics.renderer('canvas', {
        el: 'viewport',
        width: 500,
        height: 400
    });
    world.add(renderer);

    

    var shelf = Physics.body('convex-polygon', {
        x: 250,
        y: 200,
        vertices: [{
            x: -100,
            y: -10
        }, {
            x: 100,
            y: -10
        }, {
            x: 100,
            y: 10
        }, {
            x: -100,
            y: 10
        }],
        mass: 100,
        restitution: 0.5
    });
    world.add(shelf);

    var ball = Physics.body('circle', {
        x: 175,
        y: 50,
        radius: 20,
        mass: 10
    });
    world.add(ball);

    world.add(Physics.integrator('verlet', {
        drag: 0.003
    }));
    

    var pinConstraints = Physics.behavior('pin-constraints');
    // add a pin constraint constraining the shelf's center to its current position
    pinConstraints.add( shelf, shelf.state.pos );
    world.add(pinConstraints);

    world.add(Physics.behavior('constant-acceleration'));
    world.add(Physics.behavior('body-collision-detection'));
    world.add(Physics.behavior('body-impulse-response'));
   ...