Created
July 16, 2024 18:36
-
-
Save RJ-Infinity/609b3e6d3fd993157efe85944db4b744 to your computer and use it in GitHub Desktop.
a js file for rendering text into a canvas with line wrapping.
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
| CanvasRenderingContext2D.prototype._textWrap = function(text, x, y, width, renderTextFn){ | |
| let size = this.measureText(text); | |
| let height = size.fontBoundingBoxDescent + size.fontBoundingBoxAscent | |
| if (size.width > width){ | |
| let words = text.split(" ").reverse(); | |
| let thiswords = []; | |
| do{ | |
| thiswords.push(words.pop()); | |
| size = this.measureText(thiswords.join(" ")) | |
| }while (size.width < width); | |
| if (thiswords.length == 1) { | |
| let letters = thiswords[0].split("").reverse(); | |
| let thisletters = []; | |
| do{ | |
| thisletters.push(letters.pop()); | |
| size = this.measureText(thisletters.join("")) | |
| }while(size.width < width); | |
| if (thisletters.length > 1){letters.push(thisletters.pop());} | |
| text = thisletters.join(""); | |
| words.push(letters.reverse().join("")) | |
| }else{ | |
| words.push(thiswords.pop()); | |
| text = thiswords.join(" "); | |
| } | |
| height += this.fillTextWrap(words.reverse().join(" "), x, y+height, width); | |
| } | |
| renderTextFn(text, x, y + size.fontBoundingBoxAscent); | |
| return height; | |
| }; | |
| OffscreenCanvasRenderingContext2D.prototype._textWrap = CanvasRenderingContext2D.prototype._textWrap; | |
| CanvasRenderingContext2D.prototype.fillTextWrap = function(t, x, y, w){return this._textWrap(t, x, y, w, this.fillText.bind(this));} | |
| OffscreenCanvasRenderingContext2D.prototype.fillTextWrap = function(t, x, y, w){return this._textWrap(t, x, y, w, this.fillText.bind(this));} | |
| CanvasRenderingContext2D.prototype.strokeTextWrap = function(t, x, y, w){return this._textWrap(t, x, y, w, this.strokeText.bind(this));} | |
| OffscreenCanvasRenderingContext2D.prototype.strokeTextWrap = function(t, x, y, w){return this._textWrap(t, x, y, w, this.strokeText.bind(this));} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment