JSFiddle - React, Tailwind, and code Playground

by corinnekm

HTML

<body>
        <div id="content">
            <canvas id="canvas" height="500" width="500"></canvas>
        </div>
    </body>

CSS

#content {
    height: 500px;
    width: 500px;
    margin: 0 auto;
}
#canvas {
    border: solid black 1px;
}

JavaScript

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    img,
    blankCanvas = true;


var initializeCvs = function () {
    ctx.lineCap = "round";
    ctx.save();
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.restore();

    if (window.localStorage) {
        img = new Image();
        img.onload = function () {
            ctx.drawImage(img, 0, 0);
        };
        if (localStorage.curImg) {
            img.src = localStorage.curImg;
            blankCanvas = false;
        }
    }
}


var storeHistory = function () {
    img = canvas.toDataURL("image/png");
    history.pushState({
        imageData: img
    }, "", window.location.href);

    if (window.localStorage) {
        localStorage.curImg = img;
    }

};

var draw = {
    isDrawing: false,
    mousedown: function (coordinates) {
        if (blankCanvas) {
            storeHistory();
            blankCanvas = false;
        }
        ctx.beginPath();
        ctx.moveTo(coordinates.x, coordinates.y);
        this.isDrawing = true;
    },
    mousemove: function (coordinates) {
        if (this.isDrawing) {
            ctx.lineTo(coordinates.x, coordinates.y);
            ctx.stroke();
        }
    },
    mouseup: function (coordinates) {
        this.isDrawing = false;
        ctx.lineTo(coordinates.x, coordinates.y);
        ctx.stroke();
        ctx.closePath();
        storeHistory();
    }
};

function setupDraw(e) {
    var cnt = document.getElementById("content"),
        coordinates = {
            x: e.pageX - cnt.offsetLeft,
            y: e.pageY - cnt.offsetTop
        };
    draw[e.type](coordinates);
};

window.onpopstate = function (event) {
    if (event.state !== null) {
        img = new Image();
        img.onload = function () {
            ctx.drawImage(img, 0, 0);
        };
        img.src = event.state.imageData;
    }
};

window.addEventListener("mousedown", setupDraw,...