JSFiddle - React, Tailwind, and code Playground

by gamealchemist

HTML

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">

JavaScript

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

ctx.fillText("Press and hold the mouse. Move it !", 30, 60);
var started = false;
var prvX = -300;
var prvY = -300;

$('#myCanvas').bind("mousedown", function (e) {
   prvX = e.offsetX;
   prvY = e.offsetY;
   started = true ;
});

$('#myCanvas').bind("mouseup", function (e) {
   started = false ;
});

$('#myCanvas').bind("mousemove", function (e) {
    if (!started) return;
    ctx.clearRect(0,0,c.width, c.height);
    ctx.beginPath();
    ctx.moveTo(prvX, prvY);
    var dx = e.offsetX - prvX;
    var dy = e.offsetY - prvY;
    if (Math.abs(dx) > Math.abs(dy)) {
        ctx.lineTo(e.offsetX, prvY);
    } else {
        ctx.lineTo(prvX, e.offsetY);
    }
    ctx.stroke();
    ctx.closePath();
});