SVG to Canvas with canvg不尊重css

Kud*_*dos 3 javascript svg raphael canvg

我正在尝试将我的SVG转换为画布以获得png.除了css定位,一切都很好.

请看这个 jsfiddle

你可以看到顶部是SVG.

我正在使用canvg在canvas元素上呈现svg.

2个svgs相互重叠,一个是100%大小,另一个是80%.我和拉斐尔一起渲染这些.

我试图在各种地方插入内联样式,如:

<style type='text/css'>![CDATA[svg{ margin: 0 auto; }]]></style>
Run Code Online (Sandbox Code Playgroud)

然而canvg只返回:

Cannot read property 'split' of undefined
Run Code Online (Sandbox Code Playgroud)

我需要画布与SVG相同.

*注意将两者都改为100%大小和圆的半径不是一个选项,这是一个非常简化的插图版本.

Yan*_*sky 5

虽然它不太理想,但一种选择是在渲染之前内联所有样式.以下是我在此项目中用于处理相同问题的内容:

function inlineAllStyles() {
    var svg_style, selector, cssText;

    for (var i = 0; i <= document.styleSheets.length - 1; i++) {
        //loop through your stylesheets
        if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf('style.css') != -1) {
            //pull out the styles from the one you want to use
            if (document.styleSheets[i].rules != undefined) {
                svg_style = document.styleSheets[i].rules
            } else {
                svg_style = document.styleSheets[i].cssRules
            }
        }
    }

    if (svg_style != null && svg_style != undefined) {
        for (var i = 0; i < svg_style.length; i++) {
            if (svg_style[i].type == 1) {

                selector = svg_style[i].selectorText;

                styles = makeStyleObject(svg_style[i]);

                // Apply the style directly to the elements that match the selctor
                // (this requires to not have to deal with selector parsing)
                d3.selectAll(selector).style(styles)
            }
        };
    }
}

 function makeStyleObject(rule) {
    var styleDec = rule.style;
    var output = {};
    var s;

    for (s = 0; s < styleDec.length; s++) {
        output[styleDec[s]] = styleDec[styleDec[s]];
        if(styleDec[styleDec[s]] === undefined) {
            //firefox being firefoxy
            output[styleDec[s]] = styleDec.getPropertyValue(styleDec[s])
        }
    }

    return output;
}

inlineAllStyles()
Run Code Online (Sandbox Code Playgroud)