JSFiddle - React, Tailwind, and code Playground
HTML
<div class="postpreview"></div>
<textarea id=top>Her e we qwe qwe qwe qwe Her e we qwe qwe qwe qwe Her e we qwe qwe qwe qwe Her e we qwe qwe qwe qwe Her e we qwe qwe qwe qwe</textarea>
<textarea id=bottom>Author</textarea>
CSS
canvas {
border: 1px dotted #aaa;
float: left;
}
textarea {
float: left;
}
.postpreview {
padding: 12px;
max-width: 680px;
overflow: hidden;
_border: 1px solid #000;
}
JavaScript
$(document).ready(function(){
// Initialize
lolipop();
});
function lolipop() {
var bgimg = new Image();
bgimg.src = "https://www.filepicker.io/api/file/o4vsk7jR2L6ugvF3l7AP/convert?w=654"
$(bgimg).load(function() {
var img = this;
var canvas = document.createElement("canvas");
var canvasOverlay = document.createElement("canvas");
var contextOverlay = canvasOverlay.getContext("2d");
var context = canvas.getContext("2d"),
imgWidth = img.width,
imgHeight = img.height,
postPreviewWidth = $(".postpreview").width(),
realimgWidth = postPreviewWidth,
realimgHeight = imgHeight * (realimgWidth/imgWidth),
top = $("#top"),
bottom = $("#bottom");
canvas.width = realimgWidth;
canvas.height = realimgHeight;
canvasOverlay.width = realimgWidth;
canvasOverlay.height = realimgHeight;
canvasOverlay.style.position = "absolute";
canvasOverlay.style.top = "12px";
canvasOverlay.style.left = "12px";
context.drawImage(img, 0 , 0, realimgWidth, realimgHeight);
context.fillStyle = "rgba(0, 0, 0, .1)";
context.fillRect (0, 0, realimgWidth, realimgHeight);
// Setup basic canvas settings
$.extend( contextOverlay, {
shadowColor : "#000000",
shadowOffsetX : 0,
shadowOffsetY : 1,
textAlign : 'center',
textBaseline: 'middle',
font : 'bold 16px Helvetica Neue',
fillStyle : "#ffffff",
lineCap : "round"
});
var text = top.val();
var maxWidth = realimgWidth * .9;
var maxHeight = realimgHeight * .50;
console.log("maxHeight = " + maxHeight);
var x = realimgWidth/2;
var y = realimgHeight/2;
var fontSize = 16;
var lineHeight = 16;
var textHeight = 50;
textHeightCheck(contextOverlay, text, x, y, maxWidth, maxHeight, textHeight, fontSize, lineHeight, realimgWidth,...