Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"use strict";
var fragmentText = function(ctx, lines, index, maxWidth) {
var line = lines[index];
var nextLine;
var tooLong = true;
while (tooLong) {
var width = ctx.measureText(line.join(" ")).width;
if (width > maxWidth && line.length > 1) {
nextLine = nextLine || [];
nextLine.unshift(line.pop());
} else {
tooLong = false;
}
}
if (nextLine) {
lines.push(nextLine);
fragmentText(ctx, lines, index + 1, maxWidth);
}
};
var canvasText = function(width, height, text, params) {
if (!params) params = {};
text = String(text);
var fontFamily = params.fontFamily || "Arial",
fontSize = params.fontSize || 20,
fontWeight = params.fontWeight || "normal",
fillStyle = params.fillStyle || "black",
strokeStyle = params.strokeStyle || null,
strokeWidth = +params.strokeWidth;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.textAlign = "center";
context.font = [fontWeight, fontSize + "px", fontFamily].join(" ");
if (fillStyle) {
context.fillStyle = fillStyle;
}
if (strokeStyle) {
context.strokeStyle = strokeStyle;
context.lineWidth = strokeWidth;
context.lineCap = "round";
context.lineJoin = "round";
}
var lines = [text.trim().split(" ")];
fragmentText(context, lines, 0, width);
var fontHeight = context.measureText("M").width; // font height approximation
var lineHeight = params.lineHeight || fontHeight * 1.3;
var totalHeight = lines.length * lineHeight;
var currentY = (height - totalHeight) / 2 + fontHeight;
lines.forEach(function(line) {
if (strokeStyle) context.strokeText(line.join(" "), width / 2, currentY);
context.fillText(line.join(" "), width / 2, currentY);
currentY += lineHeight;
});
return canvas;
};
module.exports = canvasText;
@kentaromiura

This comment has been minimized.

Copy link

@kentaromiura kentaromiura commented Oct 23, 2018

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment