Last active
May 25, 2020 12:07
-
-
Save geblanco/38de499a28310e475601fe816ae0cde2 to your computer and use it in GitHub Desktop.
Generate a square icon of any given size with a given text. Useful to easily create favicons based on text. Used in https://github.com/m0n0l0c0/Pomodoro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// requires canvas, npm i canvas | |
var Canvas = require('canvas') | |
var fs = require('fs') | |
// Constants | |
var DIM = { width : 24, border : 1.3, font : 14 } | |
var COLOR = { light: '#ec9a97', text:'#3189cc' , border:'#e13d35' } | |
function paintCircularText(filePath=null, text=null, fill=false, border=true, callback=null){ | |
callback = callback ? callback : function(){} | |
if (!filePath || !text) { | |
return callback('Must provide text and path to write the file!') | |
} | |
var canvas = new Canvas( DIM.width, DIM.width ) | |
var ctx = canvas.getContext('2d') | |
ctx.beginPath() | |
if (fill) { | |
ctx.arc( DIM.width / 2, DIM.width / 2, ( DIM.width / 2) - Math.floor( DIM.border ), 0, 2 * Math.PI, false) | |
ctx.fillStyle = COLOR.light | |
ctx.fill() | |
} | |
if (border) { | |
ctx.lineWidth = Math.floor( DIM.border ) | |
ctx.strokeStyle = COLOR.border | |
ctx.stroke() | |
} | |
ctx.font = DIM.font + 'px Lato' | |
ctx.textAlign = 'center' | |
ctx.textBaseline = 'middle' | |
ctx.fillStyle = COLOR.text | |
ctx.fillText( text, DIM.width / 2, DIM.width / 2 ) | |
canvas.toBuffer( function( err, buffer ){ | |
if (err) { | |
return callback( err ) | |
} | |
fs.writeFile( filePath, buffer, function(err, success){ | |
if (err) { | |
return callback( err ) | |
} | |
callback( null, filePath ) | |
}); | |
}); | |
} | |
// Config variables | |
var filePath = 'icon.png' | |
var text = 'FAV' | |
var fill = false | |
var border = false | |
DIM.width = 20 | |
var callback = console.log.bind(console, '[CALLBACK]') | |
paintCircularText(filePath, text, fill, border, callback) | |
module.exports = paintCircularText |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment