我正在尝试让这个 CSS 标志 Sprite 库在我的 D3 Force 布局图中渲染
但是,似乎没有任何内容呈现。这是相同的代码笔。
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/