Skip to content

Instantly share code, notes, and snippets.

@6sRyuSK
Last active February 8, 2021 08:09
Show Gist options
  • Save 6sRyuSK/6ae6062544b3281cf27dbb64f2390c37 to your computer and use it in GitHub Desktop.
Save 6sRyuSK/6ae6062544b3281cf27dbb64f2390c37 to your computer and use it in GitHub Desktop.
var Replace2CanvasFont = pc.createScript('replace2canvasFont');
// initialize code called once per entity
Replace2CanvasFont.prototype.initialize = function() {
this.app.root.findComponents('element').forEach(function(elm){
if(elm.type === 'text') {
var font = new pc.CanvasFont(pc.app, {
fontName: 'UD Digi Kyokasho N-R, Helvetica, arial, sans-serif',
fontSize: 128,
});
font.createTextures(elm.text);
elm.font = font;
}
});
};
/*jshint esversion: 6, asi: true, laxbreak: true*/
const Replace2CanvasFont = pc.createScript('replace2canvasFont');
Replace2CanvasFont.attributes.add('fonts', {
type: 'string',
array: true,
default: ['https://fonts.googleapis.com/css2?family=Kosugi+Maru&display=swap']
});
// initialize code called once per entity
Replace2CanvasFont.prototype.initialize = function() {
if(this.fonts.length) {
const style = document.createElement('style');
const fontnames = this.fonts.map(fonturl => new URL(fonturl).searchParams.get('family').split(':')[0])
const fonturls = this.fonts.map(fonturl => '@import url(' + fonturl + ');')
style.innerHTML = fonturls.join('\n')
style.onload = () => document.fonts.load('12px ' + fontnames.join(', ')).then(fontFaces => {
const families = fontFaces.map(fontFace => fontFace.family)
this.replace(families)
})
document.body.appendChild(style)
} else {
this.replace()
}
};
Replace2CanvasFont.prototype.replace = function(families = []) {
this.app.root.findComponents('element').forEach(elm => {
if(elm.type === 'text') {
var font = new pc.CanvasFont(pc.app, {
fontName: [...families, 'arial', 'sans-serif'].join(', '),
fontSize: 128,
});
font.createTextures(elm.text);
elm.font = font;
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment