Skip to content

Instantly share code, notes, and snippets.

@kamicane
Created April 15, 2015 15:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamicane/7e2dcb2615679f59b414 to your computer and use it in GitHub Desktop.
Save kamicane/7e2dcb2615679f59b414 to your computer and use it in GitHub Desktop.
"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
Copy link

Thanks!

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