JSFiddle - React, Tailwind, and code Playground

by gravi2

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p2.js/0.6.0/p2.js"></script>
<canvas width="600" height="400" id="myCanvas"></canvas>

JavaScript

var canvas, ctx, w, h, world, boxBody, planeBody, mouseConstraint, mouseBody;

      var scaleX = 50, scaleY = -50;

      init();
      animate();

      function init(){

        // Init canvas
        canvas = document.getElementById("myCanvas");
        w = canvas.width;
        h = canvas.height;

        ctx = canvas.getContext("2d");
        ctx.lineWidth = 0.05;

        // Init p2.js
        world = new p2.World();

        // Add a box
        boxShape = new p2.Rectangle(3);
        boxBody = new p2.Body({
          mass:1,
          position:[0,3],
          angularVelocity:1
        });
        boxBody.addShape(boxShape);
        world.addBody(boxBody);

        // Add a plane
        planeShape = new p2.Plane();
        planeBody = new p2.Body();
        planeBody.addShape(planeShape);
        world.addBody(planeBody);

        // Create a body for the cursor
        mouseBody = new p2.Body();
        world.addBody(mouseBody);

        canvas.addEventListener('mousedown', function(event){

          // Convert the canvas coordinate to physics coordinates
          var position = getPhysicsCoord(event);

          // Check if the cursor is inside the box
          var hitBodies = world.hitTest(position, [boxBody]);

          if(hitBodies.length){

            // Move the mouse body to the cursor position
            mouseBody.position[0] = position[0];
            mouseBody.position[1] = position[1];

            // Create a RevoluteConstraint.
            // This constraint lets the bodies rotate around a common point
            mouseConstraint = new p2.RevoluteConstraint(mouseBody, boxBody, {
              worldPivot: position,
              collideConnected:false
            });
            world.addConstraint(mouseConstraint);
          }
        });

        // Sync the mouse body to be at the cursor position
        canvas.addEventListener('mousemove', function(event){
          var position = getPhysicsCoord(event);
         ...