JSFiddle - React, Tailwind, and code Playground
by vijayweb
HTML
<canvas id="myCanvas" width="555" height="327"></canvas>
<input id="textsample" type="text">
JavaScript
$(function() {
var cvs = $("canvas"),
cvsWidth = cvs.width(),
cvsHeight = cvs.height(),
ctx = cvs[0].getContext("2d"),
top = $("#top"),
bottom = $("#bottom");
// Setup basic canvas settings
$.extend( ctx, {
strokeStyle : "#000000",
textAlign : 'center',
fillStyle : "#ffffff",
lineCap : "round"
})
$("<img />")
.load(function() {
var img = this;
$(document.body).on("keyup", function() {
function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
ctx.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
ctx.fillText(line, x, y);
}
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect( 0, 0, 555, 327 );
var maxWidth = 400;
var lineHeight = 25;
var x = (canvas.width - maxWidth) / 2;
var y = 60;
var text = $("#textsample").val();
ctx.font = '16pt Calibri';
ctx.fillStyle = '#333';
wrapText(ctx, text, x, y, 555, 25);
}).trigger("keyup");
}).attr("src", "http://troll.me/images/one-does-not-simply/one-does-not-simply.jpg");
});