JSFiddle - React, Tailwind, and code Playground

by KomathiKarunakaran

HTML

<p>Click once to set starting rectangle position</p>
<p>Click again to set the ending position & draw rectangle</p>
<canvas id="canvas" width=300 height=300></canvas>

CSS

body {
            background-color: ivory;
        }
        canvas {
            border:1px solid red;
        }

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;

var isDrawing = false;
var startX;
var startY;

function handleMouseDown(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);
    $("#downlog").html("Down: " + mouseX + " / " + mouseY);

    // Put your mousedown stuff here
    if (isDrawing) {
        isDrawing = false;
        ctx.beginPath();
        ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
        ctx.fill();
        canvas.style.cursor = "default";
    } else {
        isDrawing = true;
        startX = mouseX;
        startY = mouseY;
        canvas.style.cursor = "crosshair";
    }

}

$("#canvas").mousedown(function (e) {
		console.log(e)
    handleMouseDown(e);
});