Is there a way for me to personally convert a font icon to .svg format?

Is there a way to retrieve an icon from a font without using third-party services? Or can fonts icons be converted to .svg format through a specific process?

Answer №1

For Windows users, one method I used was to install the desired font locally and then access Character Map to locate the specific symbol I needed. After copying it, I opened Illustrator and created an empty text box where I pasted the symbol, then switched to the icon font.

Next, by simply right clicking and converting the text to outline, I was able to export it as an SVG file.

If you don't have access to Illustrator, consider trying a similar approach using Inkscape (which is free).

Answer №2

Decode icon symbols using opentype.js

If your collection of icons lacks SVG formats, you can utilize opentype.js to interpret and transform font glyphs.

After parsing the font file, you can iterate through all glyphs available and generate an SVG <path> output using the method Glyph.getPath(x, y, fontSize).

Illustration: create spritesheet from a font file

let fontFile = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2";

// initialization
loadFont(fontFile, processFont);

//default parameters
let params = {
  fontSize: 100,
  decimals: 2
};

// processing the font file after loading and parsing
function processFont(font) {
  showGlyphs(font, params)
}


// generating SVG sprites from font glyphs
function showGlyphs(font, params) {
  // sanitizing font name
  let fontFamily = font.tables.name.fontFamily.en.replaceAll(' ', '_').replaceAll('.', '_');
  let unitsPerEm = font.unitsPerEm;
  let ratio = params.fontSize / unitsPerEm;
  let ascender = font.ascender;
  let descender = Math.abs(font.descender);
  let lineHeight = (ascender + descender) * ratio;
  let baseline = +((100 / (ascender + descender)) * descender).toFixed(3) + 2;

  let decimals = params.decimals;
  let glyphs = font.glyphs.glyphs;
  let keys = Object.keys(glyphs).length;
  let htmlOutput = '';
  let useMarkup = '';

  for (let i = 0; i < keys; i++) {
    let glyph = glyphs[i];
    let lineHeight = (ascender + descender) * ratio;
    let leftSB = glyph.leftSideBearing * ratio;
    let rightSB = (glyph.advanceWidth - glyph.xMax) * ratio;
    let glyphW = (glyph.advanceWidth) * ratio;
    let poxX = 0;

    // adjusting negative widths
    if ((glyph.advanceWidth + leftSB) < 0) {
      glyphW = Math.abs(leftSB) + Math.abs(glyph.advanceWidth) + Math.abs(rightSB);
      poxX = Math.abs(leftSB);
    }

    // obtaining svg path data
    let path = glyph.getPath(
      poxX,
      ascender * ratio,
      params.fontSize
    ).toSVG(decimals);


    if (Object.hasOwn(glyph, 'points')) {
      // adding symbol definitions
      htmlOutput += `<symbol id="symbol_${glyph.name}" data-id="${glyph.index}" viewBox="0 0 ${+(glyphW).toFixed(2)} ${+(lineHeight).toFixed(2)}"> ${path}</symbol>`;

      // incorporating visible <use> instances
      useMarkup += `<svg id="use_wrap_${glyph.name}"  viewBox="0 0 ${+(glyphW).toFixed(2)} ${+(lineHeight).toFixed(2)}"><use href="#symbol_${glyph.name}" /></svg>`;
    }
  }

  // adding hidden svg sprite
  htmlOutput = `<svg xmlns="http://www.w3.org/2000/svg" id="sprite_${fontFamily}" style="width:0; height:0; position:absolute; overflow:hidden;">` + htmlOutput + `</svg>` + useMarkup;

  // rendering html
  svgcontainer.innerHTML = htmlOutput;

}


/**
 * load font via opentype.js
 * decompress woff2 to truetype using
 * https://github.com/fontello/wawoff2
 * Based on yne's comment:
 * https://github.com/opentypejs/opentype.js/issues/183#issuecomment-1147228025
 */
function loadFont(src, callback) {
  let buffer = {};
  let font = {};
  let ext;

  // handling file
  if (src instanceof Object) {
    // extracting file extension to skip woff2 decompression
    let filename = src[0].name.split(".");
    ext = filename[filename.length - 1];
    buffer = src[0].arrayBuffer();
  }
  // requesting url
  else {
    let url = src.split(".");
    ext = url[url.length - 1];
    buffer = fetch(src).then((res) => res.arrayBuffer());
  }
  buffer.then((data) => {
    // decompressing woff2
    if (ext === "woff2") {
      data = Uint8Array.from(Module.decompress(data)).buffer;
    }
    font = opentype.parse(data);
    callback(font);
  });
}
        svg {
            height: 5em;
            border: 1px solid #ccc;
            display: inline-block;
        }
<h1>Transform fonts into SVG</h1>
<div class="svgcontainer" id="svgcontainer"></div>
<!-- required to parse woff2 fonts -->
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ef9eff9e1e8e8bccebca0bea0bf">[email protected]</a>/build/decompress_binding.js"></script>
<script src='https://cdn.jsdelivr.net/npm/opentype.js@latest/dist/opentype.min.js'></script>

Supported File Formats:

  • woff
  • truetype
  • otf
  • woff2

Opentype.js natively cannot handle woff2 files.
Luckily github user yne found a workaround utilizing fontello's waWoff2 library. Therefore, we must also load the additional waWoff2 script.

Advanced Codepen demonstration

Answer №3

If you're looking to use icons from Font Awesome, there's no need to convert them into SVGs yourself. They provide the SVG code for each icon on their official website. You can easily download the SVG code for any icon of your choice from this link: https://github.com/FortAwesome/Font-Awesome/tree/master/svgs

On that page, you'll find SVG codes for all Regular, Solid, and Brands icons available on https://fontawesome.com/icons

To get started, visit https://fontawesome.com/icons, choose an icon you like, and locate its corresponding SVG file in the downloaded list from the link above. Simply open the SVG file in a code editor, copy the shape code, and use it in your project!

Wondering how to consume the shapes? That's a different topic...

P.S: For a convenient way to download all SVG shapes in one file, check out this link to the sprite file: https://github.com/FortAwesome/Font-Awesome/tree/master/sprites

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Navbar Component's Conditional Position Property Unresponsive in Tailwind

I am currently facing an issue with displaying and hiding a navbar based on the value of a variable. While I have managed to successfully toggle the Navbar's visibility, my problem arises when attempting to keep the Navbar constantly visible at the la ...

Retrieve option attributes using Select2's formatResult method

How to Retrieve Custom Data Attributes in select2 using <select> We are looking for the same functionality as described in the provided link. However, is there a way to access the attributes of an option element within the formatResult function? ...

Transport the unique identifier of the table row

After retrieving the list of followers from Instagram and storing it in an array in a session, I am displaying the data in a tabular format. <table class="tablesorter" cellspacing="0"> <thead> <tr> <th>&l ...

Is your WordPress one-page scroll JQuery script failing to function properly?

Currently attempting to develop a single page scroll feature. Within WordPress, my navigation contains anchor tags structured as follows: <a href="#contact">Contact</a> <a href="#about">About</a> The corresponding divs for the li ...

What is the best way to create a flexible Ul-LI menu?

Is it possible to create a flexible menu where clicking on an item does not cover other items in the menu? #demo { margin: 30px 0 50px 0; font-family: sans-serif; } #demo .wrapper { display: inline-block; width: 180px; height: 20px; position ...

The div content is being forced downward

I recently implemented a two column layout on my WordPress site, and to ensure it remains responsive when the browser width is reduced, I utilized this specific solution. While the solution generally works well, I encountered an issue where the content in ...

Google AdSense shifts entire webpage to the left

After adding the Google AdSense code to my website on one page, I noticed that the entire layout (including the top navigation, etc.) shifted slightly to the left. This shift is especially noticeable when transitioning from a page without the ad to one wit ...

An individual browsing through a different user's profile on the Django platform

I'm trying to create a feature where one user, A, can click on the profile picture of another user, B, and be redirected to B's profile automatically. Any suggestions on how I can achieve this? Take a look at my HTML code where I mentioned someth ...

What is the recommended method for adjusting the size of MyWSAT pages - using CSS, code, or a combination of both?

When accessing the default MyWSAT page on a computer, you'll notice that it is perfectly centered within the page. However, resizing the page may cause the content to become too small to read without manual adjustment. This issue seems to primarily af ...

Load CSS styles once the HTML content has been generated by the PHP script

One way to dynamically add a section of HTML during page load is by making use of PHP in the index.php file: In your index.php file, you can include a section like this: <html> <head> <link href="css/style.css" rel="stylesheet"> ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

"Keep scrolling through the div's content and then proceed with the

My layout consists of a div container that occupies 80% of the screen, with fixed sidebars on both the left and right taking up 10% each. The content within the div is quite large, so I've applied overflow: hidden to it in order to hide excess content ...

How to target and style multiple descendants of an element using CSS

Can you target multiple elements with a common ancestor in CSS using class, id, etc? For example: table.exams caption, tbody, tfoot, thead, tr, th, td If not, is there a method to select all nested elements within that particular element? ...

I encountered an issue where I am unable to subtract from jQuery's .outerHeight() within an if statement

I've been working on creating an ajax request that triggers when a div is scrolled to the bottom. I thought I had it figured out with this code, but I've run into an issue. Everything works fine without subtracting 100 from the elem.outerHeight() ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

Why is it that all the columns seem to be stacked into just one column?

I've encountered an issue while trying to slice an image using HTML/CSS. My form, which I want to display in 3 columns, instead appears in a single column. The only time it works as intended is when I place my form and another div in the command sect ...

Incorporate an onclick function into the text tag element

When working with HTML, I often use text tags like this: <text id="aaa" > text</text> I'm curious if it's possible to add an onclick event to this? I attempted the following: var a = document.getElementById('aaa'); a.el ...

Steps for creating a Bootstrap 4 numeric keypad template that automatically submits after entry of 4 characters

Struggling with the limitations of using only one id="" per element is a common challenge. Despite the difficulties faced in JavaScript and Ajax, there is an attempt to utilize them effectively. JavaScript is used to capture the #code id for user sign-in ...

Interact with just a single element at a time - the one that is

I run an online store, and I'm facing an issue with my product list. When I hover over one product, all the products become active as if I'm hovering over all of them. How can I make it so only the product I'm hovering over is active while t ...

Attempting to extract an API using JavaScript

I'm currently facing an issue with the OpenWeatherMap API where a particular field is returning undefined. Strangely, all other fields are populating correctly except for the weather condition which is accessed at weather.description. Does anyone have ...