Multiline canvas text cutout
by vijayweb
HTML
<canvas id="my_canvas1"></canvas><br />
<input type="text" id="input" value="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />
CSS
body {
background-color: #efefef;
background-image: url('http://wallpaperpassion.com/upload/18987/dubai-in-the-fog-wallpaper.jpg');
background-size:cover;
}
canvas {
outline: 1px solid #000;
}
JavaScript
var canvas = document.getElementById('my_canvas1'),
ctx = canvas.getContext('2d'),
input = document.getElementById('input'),
width = +(canvas.width = 400),
height = +(canvas.height = 250),
fontFamily = "Arial",
fontSize = "42px",
fontColour = "white";
ctx.lineWidth = 2.5;
function fragmentText(text, maxWidth) {
var words = text.split(' '),
lines = [],
line = "";
if (ctx.measureText(text).width < maxWidth) {
return [text];
}
while (words.length > 0) {
var split = false;
while (ctx.measureText(words[0]).width >= maxWidth) {
var tmp = words[0];
words[0] = tmp.slice(0, -1);
if (!split) {
split = true;
words.splice(1, 0, tmp.slice(-1));
} else {
words[1] = tmp.slice(-1) + words[1];
}
}
if (ctx.measureText(line + words[0]).width < maxWidth) {
line += words.shift() + " ";
} else {
lines.push(line);
line = "";
}
if (words.length === 0) {
lines.push(line);
}
}
return lines;
}
var colors = ['red', 'blue', 'green', 'white'];
function draw() {
ctx.save();
ctx.font = "bold " + fontSize + " " + fontFamily;
ctx.textAlign = "center";
//
ctx.fillStyle = fontColour;
var lines = fragmentText(input.value, width - parseInt(fontSize,0));
var lineWidth, lineHeight;
var linePadding = 5;
lines.forEach(function(line, i) {
lineHeight = parseInt(fontSize, 0);
lineWidth = ctx.measureText(line).width;
ctx.fillText(line, (lineWidth + linePadding) / 2, (i + 1) * (lineHeight + linePadding) - linePadding - 1);
ctx.strokeText(line, (lineWidth + linePadding) / 2, (i + 1) * (lineHeight + linePadding) - linePadding - 1);
});
ctx.restore();
}
input.onkeyup = function(e) { // keyup because we need to...