JSFiddle - React, Tailwind, and code Playground
HTML
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
<br/>
<input type="text" id="first_text"> <button id="resetInput">reset</button>
<br>
<canvas id="cv"></canvas>
<img id="bg" src="https://cloud.githubusercontent.com/assets/398893/15136779/4e765036-1639-11e6-9201-67e728e86f39.jpg" style="opacity:0;"/>
CSS
canvas{
margin:40px;
}
JavaScript
$("#resetInput").on("click",function(){
$("#first_text").val("");
drawMe();
});
$("#first_text").on("change keypress keyup keydown click",function(){
drawMe();
});
var canvas = document.getElementById('cv');
ctx = canvas.getContext('2d');
// core drawing function
var drawMe = function() {
var img = document.getElementById('bg');
canvas.width = 364;
canvas.height = 900;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.fillStyle = '#F0E7DE';
//ctx.fillRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 364, 662, 0, 0, 364,662);
ctx.fillStyle = '#E1FFC7';
var rectHeight=50;
text = $("#first_text").val();
//text ="hi hello A Number, representing the highest number of the arguments, or -Infinity if no arguments are given, if one or more arguments are not numbers";
//ctx.fillText(text,30,30)
var maxWidth = 230;
var lineHeight = 15;
var x = 20;
var y = 40;
var fontSize ="9"; var fontType="Arial";
ctx.font = fontSize + 'pt '+fontType;
const words = text.split(' ');
const incrementFactor = 30; // it adds 4 pixels to rect for each line
const maxLineLength = 30;
const paragraphCount = lineCount(text.length, maxLineLength);
var newRectHeight = paragraphCount*incrementFactor;
ctx.fillRect(10,20,250,newRectHeight);
ctx.fillStyle = 'black';
drawWords(ctx, text, x, y, maxWidth, lineHeight,rectHeight,words)
}
function wrapText(context, text, x, y, maxWidth, lineHeight, rectHeight) {
var words = text.split(' ');
return words
}
function drawWords(context, text, x, y, maxWidth, lineHeight, rectHeight, words) {
var line = '';
lineCountList = [];
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
...