Skip to content

Support variable fonts in textToPoints + WebGL rendering #7724

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 46 additions & 11 deletions src/type/p5.Font.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ const invalidFontError = 'Sorry, only TTF, OTF and WOFF files are supported.'; /
const fontFaceVariations = ['weight', 'stretch', 'style'];



class Font {
let nextId = 0;
export class Font {
constructor(p, fontFace, name, path, data) {
if (!(fontFace instanceof FontFace)) {
throw Error('FontFace is required');
Expand All @@ -62,6 +62,7 @@ class Font {
this.path = path;
this.data = data;
this.face = fontFace;
this.id = nextId++;
}

/**
Expand Down Expand Up @@ -669,14 +670,44 @@ class Font {
// convert lines to paths
let uPE = this.data?.head?.unitsPerEm || 1000;
let scale = renderer.states.textSize / uPE;
let pathsForLine = lines.map(l => this._lineToGlyphs(l, scale));

const axs = this._currentAxes(renderer);
let pathsForLine = lines.map(l => this._lineToGlyphs(l, { scale, axs }));

// restore the baseline
renderer.drawingContext.textBaseline = setBaseline;

return pathsForLine;
}

_currentAxes(renderer) {
let axs;
if ((this.data?.fvar?.length ?? 0) > 0) {
const fontAxes = this.data.fvar[0];
axs = fontAxes.map(([tag, minVal, maxVal, defaultVal, flags, name]) => {
if (!renderer) return defaultVal;
if (tag === 'wght') {
return renderer.states.fontWeight;
} else if (tag === 'wdth') {
// TODO: map from keywords (normal, ultra-condensed, etc) to values
// return renderer.states.fontStretch
return defaultVal;
} else if (renderer.textCanvas().style.fontVariationSettings) {
const match = new RegExp(`\\b${tag}\s+(\d+)`)
.exec(renderer.textCanvas().style.fontVariationSettings);
if (match) {
return parseInt(match[1]);
} else {
return defaultVal;
}
} else {
return defaultVal;
}
});
}
return axs;
}

_textToPathPoints(str, x, y, width, height, options) {

({ width, height, options } = this._parseArgs(width, height, options));
Expand Down Expand Up @@ -760,21 +791,24 @@ class Font {
return lines.map(coordify);
}

_lineToGlyphs(line, scale = 1) {
_lineToGlyphs(line, { scale = 1, axs } = {}) {

if (!this.data) {
throw Error('No font data available for "' + this.name
+ '"\nTry downloading a local copy of the font file');
}
let glyphShapes = Typr.U.shape(this.data, line.text);
let glyphShapes = Typr.U.shape(this.data, line.text, { axs });
line.glyphShapes = glyphShapes;
line.glyphs = this._shapeToPaths(glyphShapes, line, scale);

line.glyphs = this._shapeToPaths(glyphShapes, line, { scale, axs });

return line;
}

_positionGlyphs(text) {
const glyphShapes = Typr.U.shape(this.data, text);
_positionGlyphs(text, options) {
let renderer = options?.graphics?._renderer || this._pInst._renderer;
const axs = this._currentAxes(renderer);
const glyphShapes = Typr.U.shape(this.data, text, { axs });
const positionedGlyphs = [];
let x = 0;
for (const glyph of glyphShapes) {
Expand All @@ -784,11 +818,11 @@ class Font {
return positionedGlyphs;
}

_singleShapeToPath(shape, { scale = 1, x = 0, y = 0, lineX = 0, lineY = 0 } = {}) {
_singleShapeToPath(shape, { scale = 1, x = 0, y = 0, lineX = 0, lineY = 0, axs } = {}) {
let font = this.data;
let crdIdx = 0;
let { g, ax, ay, dx, dy } = shape;
let { crds, cmds } = Typr.U.glyphToPath(font, g);
let { crds, cmds } = Typr.U.glyphToPath(font, g, true, axs);

// can get simple points for each glyph here, but we don't need them ?
let glyph = { /*g: line.text[i], points: [],*/ path: { commands: [] } };
Expand Down Expand Up @@ -816,7 +850,7 @@ class Font {
return { glyph, ax, ay };
}

_shapeToPaths(glyphs, line, scale = 1) {
_shapeToPaths(glyphs, line, { scale = 1, axs } = {}) {
let x = 0, y = 0, paths = [];

if (glyphs.length !== line.text.length) {
Expand All @@ -832,6 +866,7 @@ class Font {
y,
lineX: line.x,
lineY: line.y,
axs,
});

paths.push(glyph);
Expand Down
36 changes: 27 additions & 9 deletions src/type/textCore.js
Original file line number Diff line number Diff line change
Expand Up @@ -1749,7 +1749,7 @@ function textCore(p5, fn) {
modified = true;
}
// does it exist in the canvas.style ?
else if (prop in this.canvas.style) {
else if (prop in this.textCanvas().style) {
this._setCanvasStyleProperty(prop, value, debug);
modified = true;
}
Expand Down Expand Up @@ -1913,16 +1913,16 @@ function textCore(p5, fn) {
}

// lets try to set it on the canvas style
this.canvas.style[opt] = value;
this.textCanvas().style[opt] = value;

// check if the value was set successfully
if (this.canvas.style[opt] !== value) {
if (this.textCanvas().style[opt] !== value) {

// fails on precision for floating points, also quotes and spaces

if (0) console.warn(`Unable to set '${opt}' property` // FES?
+ ' on canvas.style. It may not be supported. Expected "'
+ value + '" but got: "' + this.canvas.style[opt] + "'");
+ value + '" but got: "' + this.textCanvas().style[opt] + "'");
}
};

Expand Down Expand Up @@ -2075,7 +2075,7 @@ function textCore(p5, fn) {
Object.entries(props).forEach(([prop, val]) => {
ele.style[prop] = val;
});
this.canvas.appendChild(ele);
this.textCanvas().appendChild(ele);
cachedDiv = ele;
}
return cachedDiv;
Expand Down Expand Up @@ -2435,7 +2435,9 @@ function textCore(p5, fn) {
};

if (p5.Renderer2D) {

p5.Renderer2D.prototype.textCanvas = function () {
return this.canvas;
};
p5.Renderer2D.prototype.textDrawingContext = function () {
return this.drawingContext;
};
Expand Down Expand Up @@ -2535,15 +2537,31 @@ function textCore(p5, fn) {
}

if (p5.RendererGL) {
p5.RendererGL.prototype.textDrawingContext = function () {
if (!this._textDrawingContext) {
p5.RendererGL.prototype.textCanvas = function() {
if (!this._textCanvas) {
this._textCanvas = document.createElement('canvas');
this._textCanvas.width = 1;
this._textCanvas.height = 1;
this._textDrawingContext = this._textCanvas.getContext('2d');
this._textCanvas.style.display = 'none';
// Has to be added to the DOM for measureText to work properly!
this.canvas.parentElement.insertBefore(this._textCanvas, this.canvas);
}
return this._textCanvas;
};
p5.RendererGL.prototype.textDrawingContext = function() {
if (!this._textDrawingContext) {
const textCanvas = this.textCanvas();
this._textDrawingContext = textCanvas.getContext('2d');
}
return this._textDrawingContext;
};
const oldRemove = p5.RendererGL.prototype.remove;
p5.RendererGL.prototype.remove = function() {
if (this._textCanvas) {
this._textCanvas.parentElement.removeChild(this._textCanvas);
}
oldRemove.call(this);
};

p5.RendererGL.prototype._positionLines = function (x, y, width, height, lines) {

Expand Down
7 changes: 7 additions & 0 deletions src/webgl/p5.RendererGL.js
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,13 @@ class RendererGL extends Renderer {
};
}

remove() {
this.wrappedElt.remove();
this.wrappedElt = null;
this.canvas = null;
this.elt = null;
}

//////////////////////////////////////////////
// Geometry Building
//////////////////////////////////////////////
Expand Down
8 changes: 8 additions & 0 deletions src/webgl/p5.Texture.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ class Texture {
return this;
}

remove() {
if (this.glTex) {
const gl = this._renderer.GL;
gl.deleteTexture(this.glTex);
this.glTex = undefined;
}
}

_getTextureDataFromSource () {
let textureData;
if (this.isFramebufferTexture) {
Expand Down
Loading