在d3js中添加图像

时间:2014-05-17 12:07:30

标签: css image svg d3.js

我查了很多回复,但我无法让他们中的任何一个回复。

我正在使用d3js interactive map,我想用不同的图像填充每个州。

使用

g.selectAll("#countries")
  .append('image')
  .attr('xlink:href', 'image-uri')
  .attr('width', '500')
  .attr('height', '500')

这似乎有效,但它不会仅仅在其中一个国家/地区绘制图像(设置xy是不够的,因为该国家/地区还没有固定widthheight因此图像将始终溢出

g.selectAll("#US")
  .append('image')
  .attr('xlink:href', 'image-uri')
  .attr('width', '500')
  .attr('height', '500')

没有任何反应,顺便说一句,我们会遇到与上述情况相同的问题。

由于fill样式属性有效,我想用图像填充国家/地区,代码如下

g.selectAll("#US").style('fill', 'url(urlimage-uri)');

这使得这个国家刚刚消失,就好像没有画像(图像有效且有效)

我一直在努力解决这个问题,我似乎无法找到解决这个问题的方法。

有什么东西我不见了吗?

编辑:

我正在努力用静态图像填充它们,但我需要它们来自json源的图像。

使用

<svg id="mySvg" width="80" height="80">
    <defs id="mdef">
        <pattern id="image" x="0" y="0" height="40" width="40">
        <image x="0" y="0" width="40" height="40" xlink:href="http://www.e-pint.com/epint.jpg"></image>
    </pattern>
</defs>
</svg>

有效,但我不知道如何为每个国家设置不同的图像。

上层解决方案仅使用

g.selectAll("#countries").style('fill', 'url(#image)')

但是

g.selectAll("#US").style('fill', 'url(#image)')

让国家消失

编辑:

这就是我正在尝试动态添加模式

d3.json("json/world-top/latest.json", function(error, us) {
    var defs = map.svg.append('svg:defs');
    for (var i = 0; i < us.length; i++) {
        defs.append('svg:pattern')
            .attr('id', function () { return '#image_' + us[i].track_name; })
            .attr('patternUnits', 'userSpaceOnUse')
            .attr('width', '6')
            .attr('height', '6')
            .append('svg:image')
            .attr('xlink:href', function(){return us[i].artwork_url;})
            .attr('x', 0)
            .attr('y', 0)
            .attr('width', 6)
            .attr('height', 6);
    }
});

0 个答案:

没有答案