JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="c" width="150" height="150"></canvas>
CSS
canvas{background-color:#ccc;}
JavaScript
Layer.prototype = new BaseLayer();
function TextLayer(content, fontFamily, fontSize, fontColor) {
this.content = content;
this.fontFamily = 'Impact';
this.fontSize = fontSize;
this.fontColor = 'White';
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
this.context.font = this.fontSize + 'px ' + this.fontFamily;
this.context.fillStyle = this.fontColor;
this.context.textBaseline = "top";
this.width = this.context.measureText(content).width;
this.height = fontSize + (fontSize / 4); //Text baseline is kinda weird, so I am just adding some space!
this.canvas.width = this.width;
this.canvas.height = this.height;
this.context.save();
this.context.translate(this.width / 2, this.height / 2);
this.redraw = function() {
var fitWidth='190';
var lineHeight='1';
var context = this.context;
var text = this.content;
var startX = this.width / 2 - this.width;
var startY = this.height / 2 - this.height;
var x = startX;
var y = startY;
this.context.font = this.fontSize + 'px ' + this.fontFamily;
this.context.fillStyle = this.fontColor;
this.context.textBaseline = "top";
this.context.clearRect(startX, startY, this.canvas.width, this.canvas.height);
fitWidth = fitWidth || 0;
if (fitWidth <= 0)
{
context.fillText( text, x, y );
return;
}
var words = text.split(' ');
var currentLine = 0;
var idx = 1;
while (words.length > 0 && idx <= words.length)
{
var str = words.slice(0,idx).join(' ');
var w = context.measureText(str).width;
if ( w > fitWidth )
{
if (idx==1)
{
idx=2;
}
context.fillText( words.slice(0,idx-1).join(' '), x, y + (lineHeight*currentLine) );
currentLine++;
words = words.splice(idx-1);
idx =...