在每个切片的鼠标悬停上显示图像

时间:2018-01-29 15:10:33

标签: javascript d3.js

我想在鼠标悬停时为每个切片显示图像。如何从此脚本中的JSON数组加载图像? enter image description here

我希望工具提示显示从外部文件加载的图像。

var data = [
{
    "str_lab": „A“,
    "num": 300,
„image: “http://graphics/a.svg"
},
{
    "str_lab": „B“,
    "num": 44,
„image: “http://graphics/b.svg"

},
{
    "str_lab": „C“,
    "num": 215,
„image: “http://graphics/c.svg"
},
{
    "str_lab": „D“,
    "num": 30,
„image: “http://graphics/d.svg"
} ];

代码链接:Plunker

1 个答案:

答案 0 :(得分:1)

这是你要找的吗?

Code Plunkr with mouseover resolving images (with href) as a pattern

示例图片的

来源https://developers.google.com/speed/webp/gallery

您的数据快照:

{
    "str_lab": "A",
    "num": 100,
    "image": 'https://www.gstatic.com/webp/gallery3/2.png'
},

我必须重新排列很多svg元素(尤其是defs和中心circle)。请记住,始终建议将defs附加过滤器和模式添加到SVG而不是其中的<g>元素 AND ,如果您这样做,请确保相应的元素相应地transform

以下是您的代码中的一些相关更改:

var pattern = defs.append('pattern')
 .attr('id', 'image')
 .attr('patternUnits', 'userSpaceOnUse')
 .attr('width', 300)
 .attr('height', 300);

var image = pattern.append('image').attr('x', 0).attr('y', 0).attr('width', 124)
.attr('height', 124);

鼠标悬停中的中心圈调用d.data.image设置的模式图像:

    d3.select('pattern image')
        .attr('xlink:href', d.data.image);
    svg.select('circle.image')
        .attr('fill','url(#image)')

希望这有帮助,如果您有任何疑问,请与我联系。 :)