Skip to content

Instantly share code, notes, and snippets.

@tdwesten
Last active January 12, 2020 05:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdwesten/ff69bcbd68f45786894b1750c70f7807 to your computer and use it in GitHub Desktop.
Save tdwesten/ff69bcbd68f45786894b1750c70f7807 to your computer and use it in GitHub Desktop.
Extract glyphs from a font and build a icon-font with gulp
var opentype = require( 'opentype.js' );
var fs = require( 'fs' );
var _ = require( 'lodash' );
gulp.task( 'icons', function() {
var icons = [];
var scss = '[class^="my-icon-"], [class*=" my-icon-"] { display: inline-block; font: normal normal normal 14px/1 "mylaps-icons"; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }';
opentype.load( manifest.dependencies.icons.font[ 0 ], function( err, font ) {
if ( err ) {
alert( 'Could not load font: ' + err );
} else {
var cache = [];
var fontfile = JSON.stringify( font, function( key, value ) {
if ( typeof value === 'object' && value !== null ) {
if ( cache.indexOf( value ) !== -1 ) {
return;
}
cache.push( value );
}
return value;
} );
cache = null;
font_json = JSON.parse( fontfile );
_.each( font_json.glyphs.glyphs, function( val, key ) {
if ( val.unicode ) {
val.cssClass = 'my-icon-' + convertToSlug( val.name );
val.unicode = formatUnicode( val.unicode );
icons.push( val );
var string = '.' + val.cssClass + ' { &::before {content: "\\' + val.unicode + '"; } }\n';
scss = scss + string;
}
} );
fs.writeFile( manifest.dependencies.icons.json[ 0 ], JSON.stringify( icons ), function( err ) {
if ( err ) {
return console.log( err );
}
console.log( manifest.dependencies.icons.json + " was saved!" );
} );
fs.writeFile( manifest.dependencies.icons.scss[ 0 ], scss, function( err ) {
if ( err ) {
return console.log( err );
}
console.log( manifest.dependencies.icons.scss + " was saved!" );
} );
}
} );
function convertToSlug( Text ) {
return Text
.toLowerCase()
.replace( '-', '' )
.replace( / /g, '-' )
.replace( /[^\w-]+/g, '' )
.replace( '--', '-' );
}
function formatUnicode( unicode ) {
unicode = unicode.toString( 16 );
if ( unicode.length > 4 ) {
return ( "000000" + unicode.toUpperCase() ).substr( -6 );
} else {
return ( "0000" + unicode.toUpperCase() ).substr( -4 );
}
}
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment