我有以下单词和颜色数组:
let dat = [{"word": "Lorum", "color": "red"},
{"word": "ipsum", "color": "green"},
{"word": "dolor", "color": "blue"},
{"word": "sit", "color": "purple"},
{"word": "amet", "color": "yellow"},
{"word": "consectetur", "color": "orange"},
{"word": "adipiscing", "color": "red"},
{"word": "elit", "color": "purple"},
{"word": "sed", "color": "blue"},
{"word": "eiusmod", "color": "blue"},
{"word": "tempor", "color": "green"}];
使用 d3.js,我想:(1)沿 x 轴均匀地间隔这些单词; (2) 将单词相应地换行到给定的宽度(将单词移动到下一行)。
I started a jsfiddle here,但现在的单词都共享 x 和 y 坐标。我希望它以句子的形式出现。
最佳答案
添加了以下代码,该代码将使用 foreignObject
来附加数据,就像我们在 HTML 中所做的那样。现在,只需进行少量操作,我就添加带有所需颜色属性的 span
标记。
const width = 400,
height = 400;
let svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
let dat = [{
"word": "Lorum",
"color": "red"
},
{
"word": "ipsum",
"color": "green"
},
{
"word": "dolor",
"color": "blue"
},
{
"word": "sit",
"color": "purple"
},
{
"word": "amet",
"color": "yellow"
},
{
"word": "consectetur",
"color": "orange"
},
{
"word": "adipiscing",
"color": "red"
},
{
"word": "elit",
"color": "purple"
},
{
"word": "sed",
"color": "blue"
},
{
"word": "eiusmod",
"color": "blue"
},
{
"word": "tempor",
"color": "green"
}
];
const a = svg.append("foreignObject")
.attr("width", 300)
.attr("height", 200)
.append("xhtml:body")
.append('div')
.attr('id', 'foriegnBody')
.style("font", "14px 'Helvetica Neue'")
for (const data of dat) {
const value = document.getElementById('foriegnBody').innerHTML;
if (value) {
a.html(`${value} <span style="color: ${data.color}">${data.word}</span>`)
} else {
a.html(`<span style="color: ${data.color}">${data.word}</span>`)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
关于javascript - 如何使用 d3.js 按单个单词分隔和包装 SVG 文本元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469204/