JSFiddle - React, Tailwind, and code Playground

by jonnyc

HTML

<html>
<head>
<title>Canvas</title>
<script type="text/javascript">
// When the window has loaded, DOM is ready. Run the draw() function.

</script>
</head>
<body>
    <p id="particleCount">particle count: </p><br/>

  <canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>

CSS

#myCanvas{
    border:thick black solid;
    background:white;
}

JavaScript

draw();


// When the window has loaded, DOM is ready. Run the draw() function.
var maxVelocity = 1.5;

var particles = [];

var CANVAS_HEIGHT = 400;
var CANVAS_WIDTH = 400;
var particleCount = 100;

var FPS = 33;
var particleRadius = 10;
var constDistance = Math.pow((particleRadius * 2), 2);
var collisionDetect = false;
var particleColor = "rgba(0, 255, 230, 1)";

var arcOptimised = 2 * Math.PI;

function createParticle(context) {
    this.context = context;
    this.radius = particleRadius;

    this.velocityx = 1 + (Math.random() * maxVelocity);
    this.velocityy = 1 + (Math.random() * maxVelocity);
    
    var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
    this.velocityx *= plusOrMinus;
    this.velocityy *= plusOrMinus;

    this.setPosition = function(x, y) {
        this.x = x;
        this.y = y;
    };

    this.update = function() {
        this.x = this.x + this.velocityx;
        this.y = this.y + this.velocityy;

        this.checkBounds();
        if (collisionDetect) {
            this.collisionDetect();
        }
    };

    this.collisionCheck = function(p) {
        // return false;
        return Math.pow((p.x - this.x), 2) + Math.pow((p.y - this.y), 2) > constDistance;

    };

    this.collisionDetect = function() {
        var me = this;
        particles.forEach(function(p) {
            //    this = me;
            if (p !== me) {
                if (me.collisionCheck(p)) {
                    me.velocityx = -me.velocityx;
                    me.velocityy = -me.velocityy;

                    // move it
                }
            }
            else {
                //  alert("same");
            }
        });
    };


    this.checkBounds = function() {
        if (this.x >= CANVAS_WIDTH) {
            this.velocityx = -this.velocityx;
            this.x = CANVAS_WIDTH;
        }
        else if (this.x <= 0) {
            this.velocityx = -this.velocityx;
            this.x = 0;
        }

        if (this.y >= CANVAS_HEIGHT) {
   ...