JSFiddle - React, Tailwind, and code Playground

by Anov Siradj

HTML

<p>Drag to draw. Use buttons to change lineWidth/color</p>
<canvas id="canvas" width=300 height=300></canvas>
<br>
<button id="undo">Hold this button down to Undo</button>
<br>
<br>
<button id="brush5">5px Brush</button>
<button id="brush10">10px Brush</button>
<button id="brushRed">Red Brush</button>
<button id="brushBlue">Blue Brush</button>

CSS

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

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var lastX;
var lastY;
var strokeColor = "red";
var strokeWidth = 2;
var mouseX;
var mouseY;
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var isMouseDown = false;
var brushSize = 20;
var brushColor = "#ff0000";
ctx.lineJoin = "round";

// command pattern -- undo
var points = [];


function handleMouseDown(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // Put your mousedown stuff here
    ctx.beginPath();
    if (ctx.lineWidth != brushSize) {
        ctx.lineWidth = brushSize;
    }
    if (ctx.strokeStyle != brushColor) {
        ctx.strokeStyle = brushColor;
    }
    ctx.moveTo(mouseX, mouseY);
    points.push({
        x: mouseX,
        y: mouseY,
        size: brushSize,
        color: brushColor,
        mode: "begin"
    });
    lastX = mouseX;
    lastY = mouseY;
    isMouseDown = true;
}

function handleMouseUp(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // Put your mouseup stuff here
    isMouseDown = false;
    points.push({
        x: mouseX,
        y: mouseY,
        size: brushSize,
        color: brushColor,
        mode: "end"
    });
}


function handleMouseMove(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // Put your mousemove stuff here
    if (isMouseDown) {
        ctx.lineTo(mouseX, mouseY);
        ctx.stroke();
        lastX = mouseX;
        lastY = mouseY;
        // command pattern stuff
        points.push({
            x: mouseX,
            y: mouseY,
            size: brushSize,
            color: brushColor,
            mode: "draw"
        });
    }
}

$("#canvas").mousedown(function (e) {
    handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
    handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
   ...