diet-okikae.com

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.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Ensuring Security: Best Practices for MongoDB Protection

Explore essential strategies for securing MongoDB, including role-based access, encryption, and network security measures.

AI's Impact on Creativity: Are We Losing the Essence?

Exploring how AI influences creativity and the importance of human involvement in the creative process.

The Future of D&D: Will Old Editions Be Erased Forever?

A discussion on the potential loss of old D&D editions and other RPGs due to Hasbro's current direction.

Navigating the Complexities of Attraction in Modern Dating

Exploring the intricate dynamics of attraction and social proof in relationships, revealing truths about human behavior.

A Breakthrough Discovery: Interleukin-3 and Alzheimer's Defense

New research reveals interleukin-3's role in combating Alzheimer's, suggesting it could enhance brain health and memory.

Mastering Network Programming: A Comprehensive Guide to Sockets

Discover the fundamentals of network programming with sockets, including practical coding examples and handling multiple clients effectively.

Unlocking the Potential of Consent in Leadership

Discover how asking for permission can enhance your leadership skills and foster trust and respect within your team.

Embracing Challenges: The Path to Personal Growth and Resilience

Discover how embracing challenges can lead to personal growth and resilience, drawing insights from literature and real-life figures.