首页 > 解决方案 > 基于数组值的d3动态url

问题描述

我正在尝试使用 D3 将图像 URL 附加到 SVG 元素。我尝试了各种代码,包括这个。

svg.append('g')
.selectAll('image')
.data(data)
.enter()
.append('image')
.attr('class', 'countryflag')
.attr('href', `https://www.musiktrends.com/images/countryflags/`

+ 
data.map(yValues)
+
`.png`)

.attr('width', 50)
.attr('height', barHeight)
.attr('x', 0)
.attr('y', yPos)
.attr(`transform', `translate(5,`+0+`)`)
;

这段代码的问题是我得到了网址中的所有国家。我只想要json数组中每个值对应的国家。

这是数据数组:

data = d3.json('data.json')
.then(data => {data
.forEach(d => {
d.country = d.country;
d.population = +d.population * 1000;
});
render(data);
});

我也尝试过编写一个函数,但是因为我对此很陌生,所以我无法弄清楚。谢谢大家。

标签: javascriptarraysd3.jsdynamic-url

解决方案


谢谢穆塔。这就是我最终做的事情,它似乎工作正常:

数据:

data = d3.json('data.json')
.then(data => {data
.forEach(d => {
    d.country = d.country;
  d.population = +d.population * 1000;
  d.flagurl = `../images/countryflags/`+d.country+`.png`;
});

console.log(data);
render(data);
});

const yPos = d => yScale(yValues(d));

图片

svg.append('g')
.selectAll('image')
.data(data)
.enter()
.append('image')
.attr('class', 'countryflag')

.attr('href', d => (d.flagurl))

.attr('width', 50)
.attr('height', 0.8*barHeight)
.attr('x', 0)
.attr('y', yPos)
.attr('opacity', 0)
.attr('transform', `translate(`+0.05*barHeight+`,`+0.1*barHeight+`)`)

// transition and delay         
.transition()
//.attr ('y', yPos)
.attr ('opacity', 1)
//.attr('height', yScale.bandwidth())

.duration(animateDuration-625)
.delay(delay+animateDuration+375)
;

推荐阅读