JSFiddle - React, Tailwind, and code Playground

by Shawn Allen

HTML

<canvas width="500" height="500"></canvas>

CSS

canvas {
    border: 1px solid #eee;
}

JavaScript

var canvas = document.querySelector("canvas"),
    context = canvas.getContext("2d"),
    pos = {x: 0, y: 0},
    drawing = false,
    step = 20;

function round(n) {
    return step * Math.round(n / step);
}

context.strokeStyle = "1px solid black";

canvas.addEventListener("mousedown", function(e) {
    drawing = true;
    pos.x = e.offsetX;
    pos.y = e.offsetY;
});

canvas.addEventListener("mousemove", function(e) {
    if (!drawing) return;
    context.beginPath();
    context.moveTo(round(pos.x), round(pos.y));
    pos.x = e.offsetX;
    pos.y = e.offsetY;
    context.lineTo(round(pos.x), round(pos.y));
    context.stroke();
    context.closePath();
});

document.addEventListener("mouseup", function(e) {
    drawing = false;
});

canvas.addEventListener("dblclick", function(e) {
    context.clearRect(0, 0, canvas.width, canvas.height);
});

setInterval(function() {
    context.save();
    context.strokeStyle = "transparent";
    context.fillStyle = "rgba(255,255,255,.01)";
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.restore();
}, 50);