使用Raphael JS将所有SVG文本节点转换为路径节点

时间:2014-05-26 20:25:50

标签: javascript svg raphael

我正在尝试编写一个RaphaelJS函数,该函数将获取Raphael paper实例中的现有文本节点并将其转换为路径。

目标是完全按照页面上显示的方式复制文本的位置,大小和属性,但是使用路径而不是文本进行渲染。我最初无法使用Raphael paper.print()函数呈现文本,因为文本是动态更新的,并且需要基于“文本”的属性才能执行此操作。将现有文本节点转换为路径将作为流程中的“最后”步骤(在文本修改完成之后)发生。

我这样做是为了消除安装字体以便以后查看或处理SVG的需要。

我面临的挑战是:

  1. 文本节点可能包含xdy定义的tspans。创建的路径必须完美地排列每个childNode字母(tspans)。

  2. 检索文本节点和每个tspan的实际位置数据。这是我遇到麻烦的地方,希望有经验的人可以帮助我。由于笔划宽度和其他属性会影响定位/ bbox值,我不确定获取文本正确定位数据的最有效方法是什么。

  3. 到目前为止我尝试了什么:

    我的代码的简单细分。

    我编写了一个自定义属性函数textFormat,它以交错的形式格式化文本。此函数解析文本节点,按每个字母将其拆分,添加新的行\n字符,并调整定位以使其看起来交错。

    textToPaths函数是一个纸质函数,它应该循环通过纸质节点,并使用Raphael paper.print()函数将所有找到的文本节点转换为路径。这是我遇到麻烦的功能。

    View the Complete JSFiddle Example Here

    问题代码
    我不确定如何获得准确一致的xy值以传递到paper.print()函数。现在,我正在使用getBoundingClientRect(),但它仍然关闭和倾斜。我的假设是笔划宽度影响x和y计算。

            //Loop through each tspan and print the path for each.
            var i,
                children = node.node.childNodes,
                len = children.length;
    
            for (i = 0; i < len; i++) {
                var tspan = children[i],
                    tspanText = tspan.innerHTML,
                    x = tspan.getBoundingClientRect().left - node.node.getBoundingClientRect().left,  //How do I get the correct x value?
                    y = tspan.getBoundingClientRect().top - node.node.getBoundingClientRect().top;  //How do I get the correcy y value?
    
                var path = paper.print(x, y, tspanText, font, fontSize),                
                    attrs = node.attrs;
                delete attrs.x;
                delete attrs.y;
                path.attr(attrs);
                path.attr('fill', '#ff0000');  //Red, for testing purposes.
            }
    

    完整代码 View the JSFiddle Example

    //Register Cufon Font
    var paper = Raphael(document.getElementById('paper'), '600', '600');
    
    var text1 = paper.text(100, 100, 'abc').attr({fill: 'none',stroke: '#000000',"stroke-width": '12',"stroke-miterlimit": '1',"font-family" : "Lobster", "font-size": '30px','stroke-opacity': '1'});
    var text2 = paper.text(100, 100, 'abc').attr({fill: 'none',stroke: '#ffffff',"stroke-width": '8',"stroke-miterlimit": '1',"font-family" : "Lobster", "font-size": '30px','stroke-opacity': '1'});
    var text3 = paper.text(100, 100, 'abc').attr({fill: '#000000',stroke: '#ffffff',"stroke-width": '0',"stroke-miterlimit": '1',"font-family" : "Lobster", "font-size": '30px','stroke-opacity': '1'});
    var text = paper.set(text1, text2, text3);
    text.attr('textFormat', 'stagger');
    
    /* paper.textToPaths
     * Description: Converts all text nodes to paths within a paper.
     *
     * Example: paper.textToPaths();
     */
    (function(R) {
        R.fn.textToPaths = function() {
            var paper   = this;
    
            //Loop all nodes in the paper.
            for (var node = paper.bottom; node != null; node = node.next ) {
                if ( node.node.style.display === 'none' || node.type !== "text" || node.attrs.opacity == "0") continue; //skip non-text and hidden nodes.
    
                //Get the font config for this text node.
                var text = node.attr('text'),
                    fontFamily = node.attr('font-family'),
                    fontSize = parseInt(node.attr('font-size')),
                    fontWeight = node.attr('font-weight'),
                    font = paper.getFont(fontFamily, fontWeight);
    
                //Loop through each tspan and print the path for each.
                var i,
                    children = node.node.childNodes,
                    len = children.length;
    
                for (i = 0; i < len; i++) {
                    var tspan = children[i],
                        tspanText = tspan.innerHTML,
                        x = tspan.getBoundingClientRect().left - node.node.getBoundingClientRect().left,  //How do I get the correct x value?
                        y = tspan.getBoundingClientRect().top - node.node.getBoundingClientRect().top;  //How do I get the correcy y value?
    
                    var path = paper.print(x, y, tspanText, font, fontSize),                
                        attrs = node.attrs;
                    delete attrs.x;
                    delete attrs.y;
                    path.attr(attrs);
                    path.attr('fill', '#ff0000');  //Red, for testing purposes.
                }
    
            }
    
        };
    })(window.Raphael);
    
    textToPaths = function() {
        //Run textToPaths
        paper.textToPaths();
    };
    
    
    /* Custom Element Attribute: textFormat 
     * Description: Formats a text element to either staggered or normal text.
     *
     * Example: element.attr('textFormat, 'stagger');
     */
    paper.customAttributes.textFormat = function( value ) {
        // Sets the SVG dy attribute, which Raphael doesn't control
        var selector = Raphael.svg ? 'tspan' : 'v:textpath',
            has = "hasOwnProperty",
            $node = $(this.node),
            text = $node.text(),
            $tspans = $node.find(selector);
    
        console.log('format');
    
        switch(value)
        {
            case 'stagger' :
                var stagger = function(el) {
                    var R = Raphael,
                        letters = '',
                        newline = '\n';
    
                    for (var c=0; c < text.length; c++) {
                        var letter = text[c],
                            append = '';
    
                        if(c < text.length - 1)
                            append = newline;
                            letters += letter+append;
                        }
                        el.attr('text', letters);
                        var children = el.node.childNodes;
    
                        var i,
                            a = el.attrs,
                            node = el.node,
                            len = children.length,
                            letterOffset = 0,
                            tspan,
                            tspanHeight,
                            tspanWidth,
                            tspanX,
                            prevTspan,
                            prevTspanRight = 0,
                            tspanDiff = 0,
                            tspanTemp,
                            fontSize,
                            leading = 1.2,
                            tempText;
                        for (i = 0; i < len; i++) {
                            tspan = children[i];
                            tspanHeight = tspan.getComputedTextLength();
                            tspanWidth = tspan.getComputedTextLength();
                            tspanX = tspan.getAttribute('x'),
                            prevTspanRight = tspan.getBoundingClientRect().right
    
                            if(tspanX !== null)
                            {
                                tspanDiff = tspanDiff + prevTspanRight - tspan.getBoundingClientRect().left;
                                var setX = parseInt(tspanX) + parseInt(tspanDiff);
                                tspan.setAttribute('x', setX);
                                tspan.setAttribute('dy', 15);
                            }
                            prevTspan = tspan;
                        }
                    }
                    stagger(this);
                    break;
                case 'normal' :
                    this.attr('text', text);
                    break;
                default :
                    this.attr('text', text);
                    break;
            }
    
            eve("raphael.attr.textFormat." + this.id, this, value);
    
            // change no default Raphael attributes
            return {};
        };
    
    staggerText = function() {
        //Run textToPaths
        text.attr('textFormat', 'stagger');
    };
    

    如果有人能帮我解决这个问题,我将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:12)

您可以使用Opentype.js将字体转换为SVG / Canvas路径命令。

lib将返回一系列路径绘图命令;这些用于绘制HTML5 <canvas>元素。

然而,使用这些命令构建SVG路径是微不足道的,因为字体转换不包含任何与Canvas路径绘制兼容的命令,这些命令与SVG路径命令不兼容。