之前我曾问过这个问题,但我没有问正确的问题所以我删除了那个旧帖子,希望能以一种有意义的方式再次提问。
我已将这些指令(https://bl.ocks.org/jfsiii/7772281)翻译成用于在SVG中创建条纹图案到d3:
var twoDefs = svg.append('defs')
.data(items)
.enter()
.append('pattern')
.attr('id', 'twoStripes')
.attr('patternUnits', 'userSpaceOnUse')
.attr('patternTransform', 'rotate(45)')
.attr('width', 4)
.attr('height', 4);
//to def add rect.
twoDefs
.append('rect')
.attr("x", 0)
.attr("y", 0)
.attr('width', 2)
.attr('height', 15)
.attr('fill', 'purple');
twoDefs
.append('rect')
.attr("x", 2)
.attr("y", 0)
.attr('width', 2)
.attr('height', 15)
.attr('fill', 'yellow');
在通过以下命令创建条形图期间调用它:
var bars = svg.selectAll(".bar")
.data(items)
.enter()
.append("rect")
.attr("class", function(d, i) {return "bar " + items[i].characters.first_character.character;})
.attr("x", function(d, i) {return d.starting_line;})
.attr("y", function(d, i) {return y(d.location);})
.attr("width", function(d, i) {return d.duration;})
.attr("height", 15)
.attr("fill","url(#twoStripes)");
.call(tip)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
只要.attr("fill","url(#twoStripes)");
语句(而不是颜色代码)附加到矩形,就会用紫色和黄色条纹线填充栏。
我遇到的问题是,任何尝试在我的数据中实际包含两个矩形矩形(例如,通过.attr('fill',function(d,i) {return "#" + items[i].characters.first_character.color});
而不是.attr('fill', 'purple');
)的颜色代码总是会产生第一个记录在被评估的数组中而不是实际要评估的项的记录。我知道这是因为twoDefs和bar之间没有明确的链接,但我不知道我需要做些什么来修改我的模式创建位以包含必要的索引信息来调用正确的记录。
items
中的数据很长,但这里有几条记录供参考:
{
"location": "Lazarus' tomb",
"starting_line": 919,
"line_text": "That blyssyd Lord þat here ded apere!",
"duration": 1,
"characters": {"first_character": {
"character": "Lazarus",
"color": "FFCC00"
}}
},
{
"location": "Lazarus' tomb",
"starting_line": 920,
"line_text": "We beleve in yow, Savyowr, Jhesus, Jhesus, Jhesus!",
"duration": 1,
"characters": {
"first_character": {
"character": "People",
"color": "7DB2B2"
},
"second_character": {
"character": "Weepers",
"color": "7D7DB2"
},
"third_character": {
"character": "Mary Magdalene",
"color": "CC0000"
},
"fourth_character": {
"character": "Martha",
"color": "339900"
}
}
},
{
"location": "Lazarus' tomb",
"starting_line": 921,
"line_text": "Of yower good hertys I have advertacyounys,",
"duration": 1,
"characters": {"first_character": {
"character": "Jesus",
"color": "00CCCC"
}}
}