I have a web app that is generating inline SVG graphics in the client on the fly based on user interaction. The graphic is defined partly by element attributes and partially by
If your css rules are not too much complicated, you can do the following steps:
Read the .css file, which contains all the css rule. If required, you can use a different css file and put it on the server, which you can only use for this purpose.
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');
Now apply the style on all the svg elements
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() + '');
var prop = attr_value[0].trim();
var value = attr_value[1].trim();
d3.selectAll(selector).each(function(d, i){
if(!this.getAttribute(prop) && !this.style[prop]){
d3.select(this).style(prop + '', value + '');
}
});
}
});
}
});
Use canvg to convert it
$('body').after('');
var canvas = document.getElementById('sm_canvas');
canvg(canvas, $("").append($('svg').clone()).html());
Get Image from the canvas
var imgData = canvas.toDataURL('image/jpeg');