JSFiddle - React, Tailwind, and code Playground

by phil_mcc

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Drawing Circles in Canvas</title>
</head>
<body>
<header>
<h1>Drawing in Canvas</h1>
</header>
<canvas id="game" width="768" height="400">
Sorry, your web browser does not support Canvas content.
</canvas>
</body>
</html>

CSS

canvas {
background: #333;
}

JavaScript

var untangleGame = {
    circles: [],
    thinLineThickness: 1,
    boldLineThickness: 5,
    lines: []
};

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

function Line(startPoint, endPoint, thickness) {
    this.startPoint = startPoint;
    this.endPoint = endPoint;
    this.thickness = thickness;
}

function drawCircle(ctx, x, y, radius) {
    ctx.fillStyle = "rgba(200, 200, 100, .9)";
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2, true);
    ctx.closePath();
    ctx.fill();
}

function drawLine(ctx, x1, y1, x2, y2, thickness) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.lineWidth = thickness;
    ctx.strokeStyle = "#cfc";
    ctx.stroke();
}

function clear(ctx) {
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function connectCircles() {
    // connect the circles to each other with lines
    untangleGame.lines.length = 0;
    for (var i = 0; i < untangleGame.circles.length; i++) {
        var startPoint = untangleGame.circles[i];
        for (var j = 0; j < i; j++) {
            var endPoint = untangleGame.circles[j];
            untangleGame.lines.push(new Line(startPoint, endPoint, untangleGame.thinLineThickness));
        }
    }
}
$(function() {
    // get the reference of canvas element.
    var canvas = document.getElementById("game");
    var ctx = canvas.getContext("2d");
    var circleRadius = 10;
    var width = canvas.width;
    var height = canvas.height;
    // random 5 circles
    var circlesCount = 5;
    for (var i = 0; i < circlesCount; i++) {
        var x = Math.random() * width;
        var y = Math.random() * height;
        untangleGame.circles.push(new Circle(x, y, circleRadius));
    }
    connectCircles();
    // Add Mouse Event Listener to canvas
    // we find if the mouse down position is on any circle
    // and set that circle as target dragging circle.
    $("#game").mousedown(function(e) {

        var mouseX =...