JSFiddle - React, Tailwind, and code Playground

by luizz

HTML

<canvas id="paint" style="border:1px solid d3d3d3; margin-top: 50px;"></canvas>

JavaScript

$(function() {
    var letsdraw = false;

    var theCanvas = document.getElementById('paint');
    var ctx = theCanvas.getContext('2d');
    theCanvas.width = 420;
    theCanvas.height = 300;

    var canvasOffset = $('#paint').offset();

    $('#paint').mousemove(function(e) {
        console.log(e.pageX, e.pageY, canvasOffset.left, canvasOffset.top);
        if (letsdraw === true) {
            ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
            ctx.stroke();
        }
    });

    $('#paint').mousedown(function() {
        // setup all of the properties for your line on mousedown, not mousemove
        letsdraw = true;
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 10;
        ctx.lineCap = 'round';
        ctx.beginPath();
        ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
    });

    $(window).mouseup(function() {
        // bind to the window mouse up, that way if you mouse up and you're not over 
        // the canvas you'll still get the release of the drawing.
        letsdraw = false;
    });
});