Code viewer for World: Plain canvas webgl World (...

// Cloned by Rahul K Johny on 2 Dec 2022 from World "Plain canvas webgl World" by Starter user 
// Please leave this clone trail here.
 

document.write(`
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Optical character recognition from Doodle</title>
    <style>
        body{
            padding: 0px 100px;
            font-family: sans-serif;
        }
        .container{
            margin-top: 50px;
        }
        .upper div{
            display: inline;
            margin-left: 100px;
            white-space: pre;
        }
        .bottom{
            margin-top: 30px;
            display: flex;
        }
        .bottom div{
            flex: 1;
            border: 1px solid rgb(118, 118, 118);
            height: 400px;
            margin: 10px;
        }
        .bottom div img{
            max-width: calc(100% - 20px);
            max-height: calc(100% - 20px);
            margin: 10px;
        }
        .bottom div textarea{
            resize: none;
            width: calc(100% - 21px);
            height: calc(100% - 21px);
            padding: 10px;
            font-size: 20px;
            outline: none;
            border: none;
        }
        .bottom div:first-child{
            margin-left: 0px;
            -webkit-box-align: center;
            -webkit-box-pack: center;
            display: -webkit-box;
        }
        .bottom div:last-child{
            margin-right: 0px;
        }

/* Some CSS styling */
#thesketchpad {
    /* Prevent nearby text being highlighted when accidentally dragging mouse outside confines of the canvas */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
.leftside {
    float:left;
    width:220px;
    height:285px;
    background-color:#def;
    padding:10px;
    border-radius:4px;
}
.rightside {
    float:left;
    margin-left:10px;
}
#sketchpad {
    float:left;
    height:300px;
    width:400px;
    border:2px solid #888;
    border-radius:4px;
    position:relative; /* Necessary for correct mouse co-ords in Firefox */
}
#clearbutton {
    font-size: 15px;
    padding: 10px;
    -webkit-appearance: none;
    background: #eee;
    border: 1px solid #888;
}

</style>
</head>

<body onload="init()">
    <div id="thesketchpad">
        <div class="leftside">
            Doodle an alphabet( or word) by tapping or dragging.<br/><br/>
             Touch and mouse supported!<br/><br/>
             Should work on most devices!(Firefox,chrome,brave,IOS and android)<br/><br/>
             Hit the initialize recognition after you're done!
             <input type="submit" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
        </div>
        <div class="rightside">
            <canvas id="sketchpad" height="300" width="400">
            </canvas>
        </div>
    </div>
        <div class="container">
            <div class="imgdiv">
    <img src="" class="thenewimg">
    </div>
        <div class="upper">
            <button id="recognize">Initialize Recognition</button>
            <div class="progress"></div>
        </div>
        <div class="bottom">
            <div>
                <textarea placeholder="text"></textarea>
            </div>
        </div>
    </div>
<script src="https://unpkg.com/tesseract.js@v2.0.0-alpha.13/dist/tesseract.min.js"></script>
</body>

`)
    var canvas,ctx;

    // Variables to keep track of the mouse position and left-button status 
    var mouseX,mouseY,mouseDown=0;

    // Variables to keep track of the touch position
    var touchX,touchY;

    // Draws a dot at a specific position on the supplied canvas name
    // Parameters are: A canvas context, the x position, the y position, the size of the dot
    function drawDot(ctx,x,y,size) {
        // Let's use black by setting RGB values to 0, and 255 alpha (completely opaque)
        r=0; g=0; b=0; a=255;

        // Select a fill style
        ctx.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";

        // Draw a filled circle
        ctx.beginPath();
        ctx.arc(x, y, size, 0, Math.PI*2, true); 
        ctx.closePath();
        ctx.fill();
    } 

    // Clear the canvas context using the canvas width and height
    function clearCanvas(canvas,ctx) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

    // Keep track of the mouse button being pressed and draw a dot at current location
    function sketchpad_mouseDown() {
        mouseDown=1;
        drawDot(ctx,mouseX,mouseY,12);
    }

    // Keep track of the mouse button being released
    function sketchpad_mouseUp() {
        mouseDown=0;
    }

    // Keep track of the mouse position and draw a dot if mouse button is currently pressed
    function sketchpad_mouseMove(e) { 
        // Update the mouse co-ordinates when moved
        getMousePos(e);

        // Draw a dot if the mouse button is currently being pressed
        if (mouseDown==1) {
            drawDot(ctx,mouseX,mouseY,12);
        }
    }

    // Get the current mouse position relative to the top-left of the canvas
    function getMousePos(e) {
        if (!e)
            var e = event;

        if (e.offsetX) {
            mouseX = e.offsetX;
            mouseY = e.offsetY;
        }
        else if (e.layerX) {
            mouseX = e.layerX;
            mouseY = e.layerY;
        }
     }

    // Draw something when a touch start is detected
    function sketchpad_touchStart() {
        // Update the touch co-ordinates
        getTouchPos();

        drawDot(ctx,touchX,touchY,12);

        // Prevents an additional mousedown event being triggered
        event.preventDefault();
    }

    // Draw something and prevent the default scrolling when touch movement is detected
    function sketchpad_touchMove(e) { 
        // Update the touch co-ordinates
        getTouchPos(e);

        // During a touchmove event, unlike a mousemove event, we don't need to check if the touch is engaged, since there will always be contact with the screen by definition.
        drawDot(ctx,touchX,touchY,12); 

        // Prevent a scrolling action as a result of this touchmove triggering.
        event.preventDefault();
    }

    // Get the touch position relative to the top-left of the canvas
    // When we get the raw values of pageX and pageY below, they take into account the scrolling on the page
    // but not the position relative to our target div. We'll adjust them using "target.offsetLeft" and
    // "target.offsetTop" to get the correct values in relation to the top left of the canvas.
    function getTouchPos(e) {
        if (!e)
            var e = event;

        if(e.touches) {
            if (e.touches.length == 1) { // Only deal with one finger
                var touch = e.touches[0]; // Get the information for finger #1
                touchX=touch.pageX-touch.target.offsetLeft;
                touchY=touch.pageY-touch.target.offsetTop;
            }
        }
    }


    // Set-up the canvas and add our event handlers after the page has loaded
    function init() {
        // Get the specific canvas element from the HTML document
        canvas = document.getElementById('sketchpad');

        // If the browser supports the canvas tag, get the 2d drawing context for this canvas
        if (canvas.getContext)
            ctx = canvas.getContext('2d');

        // Check that we have a valid context to draw on/with before adding event handlers
        if (ctx) {
            // React to mouse events on the canvas, and mouseup on the entire document
            canvas.addEventListener('mousedown', sketchpad_mouseDown, false);
            canvas.addEventListener('mousemove', sketchpad_mouseMove, false);
            window.addEventListener('mouseup', sketchpad_mouseUp, false);

            // React to touch events on the canvas
            canvas.addEventListener('touchstart', sketchpad_touchStart, false);
            canvas.addEventListener('touchmove', sketchpad_touchMove, false);
        }
    }
    function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}
const start = document.getElementById('recognize');
//const progress = document.querySelector('.progress');
const textarea = document.querySelector('textarea');
// now start text recognition
start.onclick = () => {
    var canvasimage = document.querySelector('#sketchpad');
    var dataURI = canvasimage.toDataURL();
    textarea.innerHTML = '';
    const rec = new Tesseract.TesseractWorker();
    rec.recognize(canvasimage)
      /*  .progress(function (response) {
            console.log(response);
            if(response.status == 'recognizing text'){
                progress.innerHTML = response.status + '   ' + response.progress
            }else{
                progress.innerHTML = response.status
            }
        })
        */
        .then(function (data) {
            console.log(data);
            data.text===''?textarea.innerHTML ="Recognition failed. Tesseractjs couldn't handle the awesomeness of your doodle! ( but on a serious note check logs)" :textarea.innerHTML = data.text;
            progress.innerHTML = 'Done'
        })
}