2017-04-16 113 views
0

如何将d3 SVG元素转换为画布?D3 SVG到画布

我得到这个工作对网络的Chrome浏览器,但它不是在iOS的Safari浏览器工作:

使用本实施方式。这个例子也不会在iOS上的Safari工作,但 参考Chrome桌面上的工作原理:http://bl.ocks.org/syntagmatic/1dd1acd35f77c1fc64863e42f4a405bb

功能为SVG到画布:

function svgToCanvas() { 
      // d3.select("#aloft-canvas-container").html(""); 
      var devicePixelRatio = window.devicePixelRatio || 1; 
      var canvas = d3.select("#aloft-canvas-container").append("canvas") 
       .attr("width", (width) * devicePixelRatio) 
       .attr("height", (ceilingChartHeight + topMarginFactor + xAxisTopContainerHeight) * devicePixelRatio) 
       .style("width", width + "px") 
       .style("height", (ceilingChartHeight+ topMarginFactor + xAxisTopContainerHeight) + "px") 
       .style("position", "absolute"); 
      var context = canvas.node().getContext("2d"); 
      context.scale(devicePixelRatio, devicePixelRatio); 
      // Convert SVG to Canvas 
      // see: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas 
      var DOMURL = window.URL || window.webkitURL || window; 
      var svgNode = d3.select("#meteo-barbs-container").node(), 
      serializer = new XMLSerializer(); 
      // var svgString = '<svg xmlns="http://www.w3.org/2000/svg">' + serializer.serializeToString(svgNode) + '</svg>'; 
      var svgString = '<svg xmlns="http://www.w3.org/2000/svg">' + domNodeToString(svgNode) + '</svg>';; 
      console.log(svgString); 
      var image = new Image(); 
      var svgBlob = new Blob([svgString], { 
       type: "image/svg+xml" 
      }); 
      var url = DOMURL.createObjectURL(svgBlob); 

      image.onload = function() { 
       context.drawImage(image, 0, 0); 
       DOMURL.revokeObjectURL(url); 
       d3.select("#meteo-barbs-container").remove(); 
      } 

      image.src = url; 
     }; 

在iOS系统中它绘制只有一半的画布。不知道什么是:-(发生

+0

不能确定适用于iOS的问题,但对于除铬每个浏览器,必须设置绝对您的根svg节点上的宽度和高度属性。 – Kaiido

回答

0

使用canvg库简化了这一切:-)

https://github.com/canvg/canvg

contents.convertSvgToCanvas = function (sourceSvgId, canvasContainerId, canvasId, canvasWidth, canvasHeight, callback) { 
    var serializer = new XMLSerializer(); 
    var svgNode = d3.select("#" + sourceSvgId).node(); 
    var devicePixelRatio = window.devicePixelRatio || 1; 
    d3.select("#" + canvasContainerId).append("canvas") 
     .attr("id", canvasId) 
     .attr("width", (canvasWidth) * devicePixelRatio) 
     .attr("height", (canvasHeight) * devicePixelRatio) 
     .style("position", "absolute"); 
    if (svgNode) { 
     var cv = document.getElementById(canvasId); 
     var ctx = cv.getContext("2d"); 
     var pixelRatio = window.devicePixelRatio || 1; 
     cv.style.width = cv.width + "px"; 
     cv.style.height = cv.height + "px"; 
     cv.width *= pixelRatio; 
     cv.height *= pixelRatio; 
     ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); 
     canvg(document.getElementById(canvasId), serializer.serializeToString(svgNode)); 
     callback(); 
    } 
};