Created
April 15, 2015 15:10
-
-
Save kamicane/7e2dcb2615679f59b414 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!