how to save/ export inline SVG styled with css from browser to image file

前端 未结 4 1646
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 17:43

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

4条回答
  •  北海茫月
    2021-02-01 18:01

    If your css rules are not too much complicated, you can do the following steps:

    1. 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');
      
    2. 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 + '');
                          }
                      });
                  }
             });
         }
      });
      
    3. Use canvg to convert it

      $('body').after('');
      var canvas = document.getElementById('sm_canvas');
      canvg(canvas, $("
      ").append($('svg').clone()).html());
    4. Get Image from the canvas

      var imgData = canvas.toDataURL('image/jpeg');
      

提交回复
热议问题