Styling errors when converting inline SVG to png

陌路散爱 提交于 2019-12-05 19:26:50
HumanInDisguise

I've been searching myself for a solution to export PNG with CSS created through Rickshaw (based on D3). The sole solution I found was to:

  • treat the DIVs different from the SVGs, and treat them all individually
  • convert the DIVs (and other non-SVG content) with html2canvas to canvas
  • make the CSS inline to the SVG; @thirdcreed has posted the JavaScript code and D3 selectors for that at: Rickshaw CSS/Axes in JSDOM - adapt that to your custom CSS as needed.
  • convert the SVGs into canvas with code such as

    var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html2);
    var img = '<img src="'+imgsrc+'">';      
    var canvas = document.querySelector("canvas"),
    context = canvas.getContext("2d");      
    var image = new Image;
    image.src = imgsrc;
    image.onload = function() {
      context.drawImage(image, 0, 0);
    }
    
  • merge the different canvases you have into one
  • convert into image with code such as:

    var canvasdata = canvas.toDataURL("image/png");
    var pngimg = '<img src="'+canvasdata+'">'; 
    d3.select("#pngdataurl").html(pngimg); // contains selector from D3, adjust if you don't use D3
    var a = document.getElementById("some_anchor"); // Fix for Firefox: supply an anchor-tag here that is 'display:none' in your document, otherwise download won't work
    a.download = "sample.png";
    a.href = canvasdata;
    a.click();
    

Note that every browser expect for Internet Explorer requires the SVGs to have the xmlns attribute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!