I wrote this script to add a font to the page based on assigned script attributes:
var AppendFont = pc.createScript('appendFont');
AppendFont.attributes.add('fonts', {
type: 'json',
schema: [{
name: 'file',
type: 'asset',
assetType: 'font'
}, {
name: 'name',
type: 'string'
}, {
name: 'style',
type: 'string'
}, {
name: 'weight',
type: 'string'
}],
array: true
});
// initialize code called once per entity
AppendFont.prototype.initialize = function() {
for (let i = 0; i < this.fonts.length; i++)
{
const fontface = new FontFace(this.fonts[i].name, "url("+this.fonts[i].file.getFileUrl()+")", {
style: this.fonts[i].style,
weight: this.fonts[i].weight
});
fontface.load().then(
() => {
document.fonts.add(fontface);
},
(err) => {
console.error(err);
},
);
}
};
So in editor it looks like this:
I uploaded the font files and it gave me these:
Getting the 2nd asset per file is expected as I know PlayCanvas doesn’t use the font files directly for its own UI, however for this purpose that causes a problem. When I use that file, getFileUrl() returns a link to a png which naturally doesn’t work with new FontFace().
I want to use the original .otf file, but it doesn’t let me assign that to the script attribute. I assume this is done to prevent people from using the wrong file when working with PlayCanvas UI, but is there a workaround where I can assign it?
– Chris