Skip to content

Instantly share code, notes, and snippets.

@RJ-Infinity
Created July 16, 2024 18:36
Show Gist options
  • Select an option

  • Save RJ-Infinity/609b3e6d3fd993157efe85944db4b744 to your computer and use it in GitHub Desktop.

Select an option

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.
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