How to render FontAwesome as SVG Image using Javascript?

前端 未结 3 618
感情败类
感情败类 2021-01-05 17:59

I want to render a FontAwesome icon as an SVG dynamically provide it as an image source using Javascript. I want my output to be something like this

PS - I

3条回答
  •  被撕碎了的回忆
    2021-01-05 18:48

    Why do you need it in img tag? SVG is an image! You do not need it to put in something else.

    May be I do not know something from you, but I think this is just a bad idea from you.

    My suggestion: put SVG in HTML with font-awesome icons directly:

    Your benefit from this: all modern browsers support it without any limits like in img tags or as background image.

    var divSvg = document.getElementById('svg'),
        pics =
        {
            user: {col: '00a', icon: 'f007'},
            home: {col: '08c', icon: 'f015'},
            folder: {col: '88f', icon: 'f07c'},
            gear: {col: '5a0', icon: 'f013'},
            flag: {col: '05a', icon: 'f024'},
            leaf: {col: '080', icon: 'f06c'}
        },
        svg =
    '\
        PIC\
    ';
    
    for(var title in pics)
    {
        var newSVG = svg.replace('PIC', '&#x'+pics[title].icon+';');
        //we put it in "B" tag to have a title because IE
        //does not support title attribute and title tag in SVG
        divSvg.innerHTML += '' +
                        newSVG.replace('COLOR', '#'+pics[title].col) + '';
    }
    
    divSvg.onclick = function(e)
    {
        if(e.target.tagName == 'text')
        {
            document.getElementById('output').innerHTML = 'Was clicked on ' +
                                    // we take title from "B" tag:
                                    e.target.parentNode.parentNode.title;
    
            /* if you need you can use:
            switch(e.target.parentNode.parentNode.title)
            {
                case 'user': alert('Here some procedure with user');
                case ...     YOUR CODE
                and so on... YOUR CODE
            }*/
        }
    }
    
    

    Please click on any icon.

提交回复
热议问题