Create Icon Images from Font Symbols Using Vanilla JavaScript
Written on
Chapter 1: Understanding Icons and Their Importance
Icons and symbols deliver meanings visually in a way that words cannot. We often subconsciously associate specific icons with particular concepts, transcending language barriers. Despite the existence of open-source font libraries like Font Awesome and Ionicons, along with icon hosting sites such as Flaticon, it can be advantageous to have alternative resources for situations where Internet access is limited.
Motivation Behind the Approach
As a Data Analyst in the healthcare field, I often deal with sensitive data, necessitating stringent network security. Much of my productivity hinges on working offline, which has led me to create tools that require minimal setup. This article serves as a follow-up to a previous piece, highlighting the differences in rendering font symbols compared to font emojis.
Technical Overview
The offline resource I will utilize is the pre-installed font icon library, Segoe UI Symbol, available on Windows OS. For Mac users, the equivalent is Apple Symbols, while the emoji counterpart is Apple Color Emoji.
Step 1: Generate an HTML Canvas Element with JavaScript
// Initialize default variables
const _scale = window.devicePixelRatio * 2;
const fontName = 'Segoe UI Symbol'; // Adjust as needed
let iconColor = '#00BCF2'; // Default blue color
let textIcon = '🖳'; // Example symbol
let w = 500;
let h = 500;
let fontSize, canvas, ctx, _x, _y;
// Create a canvas element
canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
fontSize = h / _scale;
canvas.style.margin = '1px auto';
canvas.style.width = ${w / _scale}px;
canvas.style.height = ${h / _scale}px;
canvas.style.border = '1px dotted #6c757d';
canvas.style.background = 'transparent';
ctx = canvas.getContext('2d');
ctx.scale(_scale, _scale);
> Note: Ensure that the scaling is correct to avoid low-resolution images. The canvas style height does not equal the canvas height.
Step 2: Set Attributes for the Canvas Element
// Configure canvas context attributes
ctx.font = ${fontSize}px ${fontName};
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.direction = 'ltr';
ctx.globalAlpha = 1.0;
ctx.fontVariantCaps = 'unicase'; // Must be 'unicase'.
ctx.fontKerning = 'auto';
ctx.fontStretch = 'normal';
ctx.imageSmoothingEnabled = true;
_x = (canvas.width / _scale) / 2;
_y = (canvas.height / _scale) / 2;
ctx.fillStyle = iconColor;
ctx.strokeStyle = iconColor;
ctx.fillText(textIcon, _x, _y); // Displaying '🖳'
Step 3: Enable Image Export as PNG
// Create a Save button
const saveBtn = document.createElement('button');
saveBtn.type = 'button';
saveBtn.value = canvas.toDataURL(); // Get base64-encoded image data
saveBtn.innerText = 'Save Symbol As Image ...';
saveBtn.style.display = 'block';
// Append button below the canvas
document.body.appendChild(saveBtn);
saveBtn.addEventListener('click', (evt) => {
let downloadLink = document.createElement('a');
downloadLink.href = evt.target.value;
downloadLink.download = 'output.png'; // Specify file name
downloadLink.click();
});
Image by Author | The HTML document displaying the rendered Canvas. The input text symbol '🖳' is now represented as an image in the browser.
Step 4: Allow Custom Color Selection
// Create a color picker
const colorPicker = document.createElement('input');
colorPicker.type = 'color';
colorPicker.value = iconColor; // Set default color
colorPicker.style.display = 'inline-block';
// Append color picker below Save button
document.body.appendChild(colorPicker);
// Update canvas color upon selection
colorPicker.addEventListener('input', (evt) => {
canvas.getContext('2d').clearRect(0, 0, w, h);
ctx.fillStyle = evt.target.value;
ctx.strokeStyle = evt.target.value;
ctx.fillText(textIcon, _x, _y);
saveBtn.value = canvas.toDataURL(); // Update output data
});
Image by Author | The color picker allows for real-time changes to the icon's color.
Step 5: Enable Custom Symbol Input
// Create a text input for custom symbols
const symbolInput = document.createElement('input');
symbolInput.type = 'text';
symbolInput.value = textIcon; // Default text icon
symbolInput.style.fontFamily = fontName;
symbolInput.style.display = 'inline-block';
symbolInput.style.inlineSize = '110px';
symbolInput.style.fontSize = '1.05em';
// Append input next to the color picker
document.body.appendChild(symbolInput);
// Render the symbol on input
symbolInput.addEventListener('input', (evt) => {
canvas.getContext('2d').clearRect(0, 0, w, h);
textIcon = evt.target.value;
ctx.fillText(textIcon, _x, _y);
saveBtn.value = canvas.toDataURL(); // Ensure output data is updated
});
Image by Author | When the symbol 'î…¯' is entered, the Canvas updates to reflect the intended graphical representation.
Conclusion
The complete HTML file for this demonstration can be accessed at demo.html. You can find the final version's source code on my GitHub repo — symbol2image, or try it out at the demo link provided.
Thank you for reading! I hope you found this guide beneficial. If you're interested in more content on Geographic Information Systems (GIS), Data Analytics, and Web Applications, feel free to follow me on Medium. Your support is appreciated!
In this video, learn how to animate Font Awesome icons using JavaScript in a straightforward tutorial.
Discover how to animate Font Awesome icons with JavaScript in this easy-to-follow YouTube tutorial.