javascript - 标记 Sprite 不在 D3 强制布局中渲染

标签 javascript d3.js

我正在尝试让这个 CSS 标志 Sprite 库在我的 D3 Force 布局图中渲染

https://www.flag-sprites.com/

但是,似乎没有任何内容呈现。这是相同的代码笔。

http://codepen.io/redixhumayun/pen/ZLELvG?editors=0010

这是我尝试渲染 Sprite 的相关代码

var node = svg.selectAll('.node')
                .data(data_nodes)
                .enter().append('svg:image')
                .attr('class', function(d){ return 'flag flag-'+d.code })
                .attr('src', 'blank.gif')
                .attr('width', '20px')
                .attr('height', '50px');

node.attr('x', function(d) { return (d.x - 5); })
        .attr('y', function(d) { return (d.y - 2); })
        .on('mouseover', function(d){
           console.log(d.country);
        })

最佳答案

您的问题是您正在使用 svg:image 元素和 flagsprites,并且其 css 设置为期望常规 html img 元素

但是,在这里获取此代码笔的一部分 --> https://codepen.io/AmeliaBR/pen/mwzBD

...您可以使用 flagsprite 图像和一些裁剪来模拟 flagsprites css 的作用

因此,使用您的 codepen,首先更改您的 html,设置一个剪辑和另一个包含标志 sprites png 的隐藏 svg 作为要引用的图像:

  <svg class='chart'>
     <clipPath id="icon-cp" >
        <rect x="0" y="0" width="16" height="11" />
    </clipPath>
  </svg>
  <svg style="display:none">
    <image id="icon-sprite" width="256" height="176" xlink:href="https://*dropbox_addy_excised_for_privacy*/country%20data%20for%20force%20directed%20graph/flags.png" />
  </svg>

这里的缺点是需要声明标志 Sprite png和 Sprite 的大小(以及图像所在的地址,我已将其删除)

然后你的 javascript 中的节点需要像这样设置:

var node = svg.selectAll('.node')
                .data(data_nodes)
                .enter().append('g')
                .attr("clip-path", "url(#icon-cp)")
  ;

  node.append("use")
                .attr("xlink:href", "#icon-sprite")
                .attr('class', function(d){
                  return 'flag flag-'+d.code 
                })
  ;

// this bit then takes the background-position style from the flag-sprite css and turns it
// into a translate coordinate for use with the transform attribute
  node.selectAll("use")
    .attr("transform", function() {
     var commaed = d3.select(this).style("background-position").replace(/[px]/g, "").replace(" ", ",");
      return "translate ("+commaed+")"
  })

节点然后像这样调整:

node.attr('transform', function(d) { return "translate ("+(d.x - 5)+","+(d.y - 2)+")"; })
        .on('mouseover', function(d){
           console.log(d.country);
        })

关于javascript - 标记 Sprite 不在 D3 强制布局中渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509228/

相关文章:

javascript - 过滤 Javascript 数组并仅返回具有填充键的对象

javascript - AngularJS:指令找不到注入(inject)的依赖项

javascript - 通过 chrome 选项卡发送鼠标移动

javascript - 如何在 MongoDB 中按引用字段查询?

javascript - D3如何创建圆轴和样式选项

d3.js - 迭代 D3js 中已经创建的节点

javascript - 使用 d3 中的选择器进行后续样式设置(仅最后一个生效)

d3.js - D3 JS数据过滤

javascript - 有没有一种简单的方法可以让非严格的 JavaScript 代码库在 'strict' 环境中运行?

javascript - 背景图像不透明度