Skip to content

Instantly share code, notes, and snippets.

@wyattisimo
Last active September 26, 2015 05:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyattisimo/1045379 to your computer and use it in GitHub Desktop.
Save wyattisimo/1045379 to your computer and use it in GitHub Desktop.
HTML5 canvas workaround for browsers that ignore the maxWidth argument of fillText() and strokeText()
/*
Workaround for browsers that ignore the maxWidth argument of fillText() and strokeText()
Sample usage:
context.fillTextW("DISPROPORTIONABLENESS", 0, 10, 50);
*/
CanvasRenderingContext2D.prototype.fillTextW = function(text, x, y, maxWidth) {
this.fillOrStrokeText("fillText", text, x, y, maxWidth);
}
CanvasRenderingContext2D.prototype.strokeTextW = function(text, x, y, maxWidth) {
this.fillOrStrokeText("strokeText", text, x, y, maxWidth);
}
CanvasRenderingContext2D.prototype.fillOrStrokeText = function(method, text, x, y, maxWidth) {
if (method != "fillText" && method != "strokeText") return;
var metrics = this.measureText(text);
if (metrics.width > maxWidth) {
var ctx = document.createElement('canvas').getContext('2d');
ctx.canvas.width = metrics.width;
ctx.canvas.height = this.canvas.height;
ctx.fillStyle = this.fillStyle;
ctx.strokeStyle = this.strokeStyle;
ctx.lineWidth = this.lineWidth;
ctx.font = this.font;
if (!this.canvas.style.direction || this.canvas.style.direction == "ltr") {
switch (this.textAlign) {
case "end":
case "right": x -= maxWidth; break;
case "center": x -= maxWidth / 2;
}
} else if (this.canvas.style.direction == "rtl") {
switch (this.textAlign) {
case "start":
case "right": x -= maxWidth; break;
case "center": x -= maxWidth / 2;
}
}
ctx.textBaseline = this.textBaseline;
ctx[method](text, 0, y);
this.drawImage(ctx.canvas, x, 0, maxWidth, ctx.canvas.height);
} else {
this[method](text, x, y);
}
}
@idwds
Copy link

idwds commented Nov 30, 2013

Awesome--much appreciated. You left one thing out that was causing a bug in my test app though:
ctx.lineWidth = this.lineWidth;

@wyattisimo
Copy link
Author

@idwds thanks. i updated the gist.

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