JSFiddle - React, Tailwind, and code Playground

by Laxmikant Dange

HTML

<canvas id="canvas" width=300 height=300></canvas><br/>
<div>
  <input type="radio" name="shape" id="clear" value="clear" checked>Clear<br>

  <input type="radio" name="shape" id="line" value="line">Line<br>

  <input type="radio" name="shape" id="select" value="select">Select<br>
</div>

CSS

body {
  background-color: ivory;
  padding: 10px;
}

canvas {
  border: 1px solid red;
}

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var offsetX = canvas.offsetLeft;
var offsetY = canvas.offsetTop;
var storedLines = [];
var startX = 0;
var startY = 0;
var isDown;
var dragok = false;
var type = "line"; // current type
ctx.strokeStyle = "orange";
ctx.lineWidth = 3;


function handleMouseDown(e) {
  e.preventDefault();
  e.stopPropagation();

  canvas.style.cursor = "crosshair";

  var mouseX = parseInt(e.clientX - offsetX);
  var mouseY = parseInt(e.clientY - offsetY);

  isDown = true;
  startX = mouseX;
  startY = mouseY;

  // test each rect to see if lines are inside
  if (type == "select") {
    dragok = false;
    for (var i = 0; i < storedLines.length; i++) {
      var r = storedLines[i];
      if (r.x1 > startX && r.x2 < (mouseX + startX) && r.y1 > startY && r.y2 < (mouseY + startY)) {
        // if yes, set that rects isDragging=true
        dragok = true;
        r.isDragging = true;
        ctx.strokeStyle = "blue";
      }
    }
  }
}

function handleMouseMove(e) {
  e.preventDefault();
  e.stopPropagation();

  if (!isDown) return;

  redrawStoredLines();

  var mouseX = parseInt(e.clientX - offsetX);
  var mouseY = parseInt(e.clientY - offsetY);

  if (type == "select") {
    ctx.beginPath();
    ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
    ctx.stroke();
    // if we're dragging anything...
    if (dragok) {

      // tell the browser we're handling this mouse event
      e.preventDefault();
      e.stopPropagation();

      // get the current mouse position
      var mx = parseInt(e.clientX - offsetX);
      var my = parseInt(e.clientY - offsetY);

      // calculate the distance the mouse has moved
      // since the last mousemove
      var dx = mx - startX;
      var dy = my - startY;

      // move each line that isDragging 
      // by the distance the mouse has moved
      // since the last mousemove
      var r = storedLines[i];
      if (r.x1 > startX && r.x2 < (mouseX +...