Last active
September 26, 2015 05:17
-
-
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()
This file contains 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
/* | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome--much appreciated. You left one thing out that was causing a bug in my test app though:
ctx.lineWidth = this.lineWidth;