我正在尝试将我的SVG转换为canvas以获得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%大小和改变圆的半径不是一个选项,这是一个非常简化的版本作为说明。
发布于 2015-02-20 00:57:16
虽然它不太理想,但一种选择是在渲染之前内联所有的样式。下面是我在this project上处理相同问题的方法
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()发布于 2017-02-02 16:55:31
如果您的css规则不是太复杂,您可以执行以下步骤:
function readTextFile(文件){ var rawFile = 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);'/css/svg_sm_dashboard.css');
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选择器= full_rule_string.trim();var all_rule = full_rule_string1.split(';');d3.selectAll(selector).style(attr_value.trim() (all_rule.forEach (elem) { if (elem.trim() != '') { var attr_value = elem.split(':');canvg + '',attr_value1.trim() + '');} });}});
$('body').after('');var canvas = document.getElementById('sm_canvas');canvg(canvas,body
https://stackoverflow.com/questions/28600801
复制相似问题