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


我正在尝试写一个 RaphaelJS 将获取现有文本节点的函数 拉斐尔纸 实例并将它们转换为路径。

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

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

我面临的挑战是:

  1. 文本节点可以包括tspans x 和 dy 定义。创建的路径必须完美地排列每个childNode字母(tspans)。

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

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

我的代码的简单细分。

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

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

在这里查看完整的JSFiddle示例

问题代码
我不确定如何获得准确和一致 x 和 y 值传入 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.
        }

完整的代码  查看JSFiddle示例

//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');
};

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


6098
2018-05-26 20:25


起源

为什么不使用嵌入式webfonts呢? - Erik Dahlström
我试图消除以后安装字体的需要。你不能在SVG中嵌入字体信息,因此我需要将文本字形转换为路径;) - Axel
当然可以,webfonts可以作为数据URI嵌入。这是一个例子: xn--dahlstrm-t4a.net/svg/fonts/webfont-datauri.svg - Erik Dahlström
这是使用嵌入式font-face很好,但像ImageMagick这样的服务器端工具不支持SVG中的font-face,这导致了同样的问题。我选择消除渲染字体的要求,期限。我想确保它看起来100%相同,而不依赖于不同的字体渲染引擎。我能保证的唯一方法是使用绝对路径。 - Axel


答案:


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

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

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


12
2018-04-20 19:53



好的图书馆,我希望我在10个月前知道这个:D - Axel
我有与Axel完全相同的问题/问题,我也在SVG编辑器中实现了Opentype.js。它就像一个魅力。一个问题:我有一个输入字段,可以更改每个键盘上的文本。但我不想在每次更改时加载字体..是不是有办法我可以“存储”某个地方的字体,只是重新调整每个文本更改的路径?有任何想法吗? - Dreamdealer
比较输入 opentype.js 并确保只发送更改的字符。然后在适当的位置重新绘制已更改的char(您将自己计算)。这样做相当复杂,但如果你想要快速的话,这是必要的。否则只需使用您的UI。允许用户键入字符,仅在完成时进行幕后转换,并“静默”用bezier表示替换字体。 - Nicholas Kyriakides