JSFiddle - React, Tailwind, and code Playground

by brigand

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<canvas id="drawCanvas" style="border:2px solid lightblue;height:400px;width:400px;"></canvas>

JavaScript

$(function() {
  class Canvas {
    constructor(canvas) {
      this.canvas = canvas;
      this.context = this.canvas.getContext("2d")
      this.clickX = new Array()
      this.clickY = new Array()
      this.clickDrag = new Array(),
        this.paint = false
      this.bind_handlers()
    }
    addClick(x, y, dragging) {
      this.clickX.push(x);
      this.clickY.push(y);
      this.clickDrag.push(this.paint);
    }
    freehand_redraw() {

      this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height); // Clears the canvas

      this.context.strokeStyle = "#df4b26";
      this.context.lineJoin = "round";
      this.context.lineWidth = 5;
      for (var i = 0; i < this.clickX.length; i++) {
        this.context.beginPath();

        if (this.clickDrag[i] && i) {
          this.context.moveTo(this.clickX[i - 1], this.clickY[i - 1]);
        } else {
          this.context.moveTo(this.clickX[i] - 1, this.clickY[i]);
        }
        this.context.lineTo(this.clickX[i], this.clickY[i]);

        this.context.closePath();
        this.context.stroke();

      }
    }
    mousedown(e) {
      this.paint = true;
      this.addClick(e.pageX - $(this.canvas).offset().left,
        e.pageY - $(this.canvas).offset().top)
      this.freehand_redraw();
    }
    mousemove(e) {
      if (this.paint) {
        this.addClick(e.pageX - $(this.canvas).offset().left,
          e.pageY - $(this.canvas).offset().top)
        this.freehand_redraw();
      }
    }
    mouseup(e) {
      this.paint = false
      this.addClick(e.pageX - $(this.canvas).offset().left,
        e.pageY - $(this.canvas).offset().top)
    }
    bind_handlers() {
      $(this.canvas).mousedown((event) => {
        this.mousedown(event);
      })
      $(this.canvas).mousemove((event) => {
        this.mousemove(event);
      })
      $(this.canvas).mouseup((event) => {
        this.mouseup(event);
      })
    }

  }

  let canvas = new...