如何使用 d3.js 将 svg 附加到预先存在的 svg?

luQ*_*luQ 2 html javascript svg d3.js angularjs

是否可以使用 d3.js 将另一个 svg 附加到预先存在的 svg 父级?

我知道可以通过使用“svg:image”属性来实现。但不幸的是,我失去了对内部 svg-child 的完全控制。

相关 dom 节点由 d3 创建,但未渲染,因此页面保持空白。

希望有人可以提供帮助,提前谢谢:)

这是我得到的:

网页CSS

  #svg-main-wrapper {
    position: absolute;
    min-width: 100%;
    min-height: 100%;
    bottom: 0;
    padding: 0;
    margin: 0;
  }
  
  
  <div id="svg-main-wrapper">
    <div svg-container svg-src="svgContainer[0].url" position="svgContainer[0].position">
    </div>    
  </div>
Run Code Online (Sandbox Code Playgroud)

JavaScript

angular.module('app', ['ui.bootstrap'])
  .directive('svgContainer', function() {
    return {
      restrict: 'A',
      template: function() {
        var parent = angular.element('body');
        return '<svg class="svg-container" width="' + parent.width() + '" height="' + parent.height() + '" viewBox=" 0 0 ' + parent.width() + ' ' + parent.height() + '"preserveAspectRatio ="xMinYMax meet"></svg>';
      },
      scope: {
        svgSrc: '=',
        position: '='
      },
      link: function(scope, element, attrs) {

        var parent = angular.element('#svg-main-wrapper');

        var x = 0;
        var y = parent.height() - 400;

        var svg = d3.select(element[0]);
        var g = svg.append('g');

        var innersvg = g.append('svg')
          .attr('xlink:href', scope.svgSrc)
          .attr('preserveAspectRatio', scope.position)
          .attr('width', parent.width())
          .attr('height', 400)
          .attr('transform', 'translate(' + x + ',' + y + ')');

      },
      replace: true
    };
  })

  .controller('ctrl', ['$scope', '$window', function($scope, $window) {

    $scope.svgContainer = [
      {
        id: 0,
        short_name: 'left',
        url: './images/complete.svg',
        position: 'none'
      }
      ];
  }]);
Run Code Online (Sandbox Code Playgroud)

Ger*_*ado 6

您的问题是:“是否可以使用 D3 将 SVG 附加到 SVG?” 标题中的那个对象有点误导(但是,如果您真的在谈论<object>甚至加载外部 SVG,那么您就做错了,以下解释将毫无用处。在这种情况下,像这样的答案会更有用)。

答案是肯定的。无论出于何种原因您想要嵌套这些 SVG(您可能不需要它),只需append像使用任何其他元素一样使用该方法即可。

这是一个演示,看看控制台:SVG 里面有一个 SVG。

var svg = d3.select("body").append("svg");
svg.append("text")
  .attr("y", 20)
  .text("this text is in the outer SVG");
var innerSVG = svg.append("svg");
innerSVG.append("text")
  .attr("y", 50)
  .text("this text is in the inner SVG");

var mySVG = (new XMLSerializer()).serializeToString(svg.node());
console.log(mySVG)
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.min.js"></script>
Run Code Online (Sandbox Code Playgroud)