JSFiddle - React, Tailwind, and code Playground

by ghostoy

HTML

<canvas id="c" width="400" height="400"></canvas><br/>
<button id="record">Record</button>
<button id="stop">Stop</button>
<button id="play">Play</button>
<button id="export">Export</button>
<textarea id="output" rows="5" cols="100"></textarea>

CSS

#c {
    border: 1px solid black;
}

JavaScript

var points = [];
var recording = false;
var down = false;

$('#c')
    .mousedown(function(e) {
        if (recording) {
            var ctx = $('#c')[0].getContext('2d');
            ctx.beginPath();
            ctx.moveTo(e.offsetX, e.offsetY);
            points.push({a: 'M', x: e.offsetX, y:e.offsetY, t: Date.now()});
            down = true;
        }
    })
    .mousemove(function(e){
        if (recording && down) {
            var ctx = $('#c')[0].getContext('2d');
            ctx.lineTo(e.offsetX, e.offsetY);
            ctx.stroke();
            points.push({a: 'L', x: e.offsetX, y:e.offsetY, t: Date.now()});
        }
    })
    .mouseup(function(e){
        if (recording && down) {
            var ctx = $('#c')[0].getContext('2d');
            ctx.lineTo(e.offsetX, e.offsetY);
            ctx.stroke();
            points.push({a: 'L', x: e.offsetX, y:e.offsetY, t: Date.now()});
            down = false;
        }
    });

$('#record').click(function() {
    $('#record').hide();
    $('#stop').show();
    points = [];
    recording = true;
    var canvas = $('#c')[0];
    canvas.width = canvas.width;
});

$('#stop').click(function(){
    $('#record').show();
    $('#stop').hide();
    recording = false;
});

$('#play').click(function() {
    $('#stop').click();
    
    var canvas = $('#c')[0];
    var ctx = canvas.getContext('2d');
    var i = 0;
    
    canvas.width = canvas.width;
    
    function draw() {
        if (i >= points.length) return;
        
        var p = points[i];
        if (p.a === 'M') {
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
        } else {
            ctx.lineTo(p.x, p.y);
            ctx.stroke();
        }
        
        i++;
        
        if (i < points.length) {
            setTimeout(draw, points[i].t - p.t);
        }
    }
    
    if (points.length) {
        draw();
    }
});

$('#export').click(function() {
    
});