JSFiddle - React, Tailwind, and code Playground

by jeffsturgis

HTML

<form id="inputs">
    <input id="top-input" type="text" placeholder="top" value="" />
    <input id="bottom-input" type="text" placeholder="bottom" value="" />
</form>
<div>

    <canvas id="preview"></canvas>
    
    <img id="original-image" src="http://imgflip.com/readImage?url=http://i.iflip.im/1bim.jpg"/>
</div>

CSS

#original-image {
    display: none;
}

JavaScript

var $canvas = $('#preview'),
    context = $canvas[0].getContext('2d'),
    image = $('#original-image')[0],
    topText = '',
    bottomText = '',
    topTextWidth = 0,
    bottomTextWidth = 0,
    minFontSize = 12,
    fontSize = 40,
    bottomFontSize = fontSize,
    topFontSize = fontSize,
    fontFamily = 'impact,impac',
    height = image.naturalHeight / 2,
    width = image.naturalWidth / 2;

// set the canvas size to half the image size
$canvas.attr('height', height).attr('width', width);

// canvas styles
context.fillStyle = '#FFF';
context.strokeStyle = '#000';
context.lineWidth = 3;
context.font = fontSize + 'px ' + fontFamily;
context.textAlign = 'center';
context.shadowBlur = 5;
context.shadowColor = '#000';

// render the image
context.drawImage(image, 0, 0, width, height);

function setFontSize(size){
    context.font = size + 'px ' + fontFamily;
}

function adjustTopFontSize(adjustType){
    
    if(topText){
        setFontSize(topFontSize);
    }
    
    // if text was added we need to reduce text size
    if(adjustType === 'reduce'){
        while(context.measureText(topText).width > width && topFontSize > minFontSize){
            topFontSize = topFontSize - 1;
            setFontSize(topFontSize);
        }
    }else if(adjustType === 'increase'){
        // if text was removed we need to increase the text size
        while(context.measureText(topText).width < width && topFontSize < fontSize ){
            topFontSize = topFontSize + 1;
            setFontSize(topFontSize);
        }        
    }
}

function adjustBottomFontSize(adjustType){

    if(bottomText){
        setFontSize(bottomFontSize);
    }
    
    // if text was added we need to reduce text size
    if(adjustType === 'reduce'){
        while(context.measureText(bottomText).width > width && bottomFontSize > minFontSize){
            
            bottomFontSize = bottomFontSize - 1;
            setFontSize(bottomFontSize);
        }
        
    }else if(adjustType ===...