SVG到Canvas,canvg不尊重css

SVG to Canvas with canvg not respecting css

本文关键字:css canvg Canvas SVG      更新时间:2024-02-08

我正试图将SVG转换为画布以获得png。除了css定位之外,一切都很好。

请看这个jsfiddle

您可以看到顶部的SVG。

我使用canvg在画布元素上渲染svg。

两个svg相互重叠,一个是100%大小,另一个是80%大小。我和拉斐尔一起绘制这些。

我试着在不同的地方插入内联样式,比如:

<style type='text/css'>![CDATA[svg{ margin: 0 auto; }]]></style>

但是canvg只返回:

Cannot read property 'split' of undefined

我需要画布与SVG完全相同。

*注意,将圆的大小和半径都更改为100%是不可行的,这是一个非常简化的版本。

虽然不太理想,但有一种选择是在渲染之前内联所有样式。以下是我在这个项目中处理相同问题的方法:

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()

如果您的css规则不是太复杂,您可以执行以下步骤:

  1. 读取.css文件,该文件包含所有css规则。如果需要,您可以使用不同的css文件并将其放在服务器上,而服务器只能用于此目的。

    function readTextFile(file) {
        var rawFile = new XMLHttpRequest();
        var allText = '';
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if(rawFile.readyState === 4) {
                if(rawFile.status === 200 || rawFile.status == 0) {
                    allText = rawFile.responseText;
                }
            }
        };
        rawFile.send(null);
        return allText;
    }
    var svg_style = readTextFile(base_url + '/css/svg_sm_dashboard.css');
    
  2. 现在将样式应用于所有svg元素

    var all_style = svg_style.replace(/'r?'n|'r/g,'').split('}');
    all_style.forEach(function(el) {
        if (el.trim() != '') {
            var full_rule_string = el.split('{');
            var selector = full_rule_string[0].trim();
            var all_rule = full_rule_string[1].split(';');
            all_rule.forEach(function (elem) {
                if (elem.trim() != '') {
                    var attr_value = elem.split(':');
                    d3.selectAll(selector).style(attr_value[0].trim() + '', attr_value[1].trim() + '');
                }
           });
       }
    });
    
  3. 现在使用canvg将其转换为

    $('body').after('<canvas id="sm_canvas" style="display=none;"></canvas>');
    var canvas = document.getElementById('sm_canvas');
    canvg(canvas, $("<div>").append($('svg').clone()).html());