JSFiddle - React, Tailwind, and code Playground

by mvasilkov

HTML

<textarea class="form-control" id="codeArea" placeholder="Paste code here"></textarea>
<button id="clicky">Generate</button>
<canvas id="myCanvas" style="display: none"></canvas>
<img id="canvasImg" style="display: none">

JavaScript

document.getElementById('clicky').onclick = draw

function draw() {
    var c = document.getElementById('myCanvas'),
        ctx = c.getContext('2d'),
        unitSize = 6;

    var s = document.getElementById('codeArea').value;
        if (s) {
            var l = s.split('\n'),
                maxLength = Math.max.apply(null,
                                           l.map(function(e) {return e.length}))
            c.height = (l.length) * (unitSize + 1);
            c.width = maxLength * unitSize/2;


            l.forEach(function(e, i) {
                var f = e.search(/\S/)*(unitSize/2)
                var g = e.trim().length*(unitSize/2)
                ctx.fillStyle = "#2980b9";
                ctx.fillRect(0, i*unitSize+i,
                             f, unitSize)
                ctx.fillStyle = "#3498db";
                ctx.fillRect(f, i*unitSize+i,
                             g, unitSize)
            })

            var canvasImg = document.getElementById('canvasImg');
            canvasImg.style.background = '#2c3e50';
            canvasImg.style.border = '10px solid #2c3e50';
            canvasImg.src = c.toDataURL();
            canvasImg.style.display = 'block';
        }
}