我创建了一个SVG文件(data / humanTest.svg):
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 800 800" style="enable-background:new 0 0 800 800;" xml:space="preserve">
<polygon fill="yellow" id="forehead" stroke="blue" stroke-width="2" points="318.1,24.6 308.7,40.3 308.7,79.6 360.6,82 378.6,46.6 370,8.9 346.4,17.5 "/>
</svg>
我要记录id&#34;额头&#34;当我将鼠标悬停在svg元素上但是当我运行我的代码时,我得到null。
这是我的d3代码:
var main_chart_svg = d3.select("#diagram")
.append("svg")
.attr({
"width": 800,
"height": 800
}).append('g');
d3.xml("data/humanTest.svg").mimeType("image/svg+xml").get(function (error, xml) {
if (error) throw error;
var svgNode = xml
.getElementsByTagName("svg")[0];
main_chart_svg.node().appendChild(svgNode);
var innerSVG = main_chart_svg.select("svg");
innerSVG.append("text")
.attr("dy", "1em")
.attr("dx", "1em")
.text("Test text");
innerSVG.on("mousemove", function (d) {
//console.log(innerSVG.id);
//d3.select("#diagram svg").selectAll("g")
console.log(d3.select(this).attr('id')); //doesnt work,
//gives me the svg id (Layer_1) not the id of the polygons within the svg tag
})
});
如果有人能帮助我,我将非常感激。
答案 0 :(得分:1)
您的innerSVG
是整个SVG。它没有名为“额头”的ID。在您的代码中,this
引用了SVG元素。
如果您只有一个多边形,请改用:
console.log(d3.select("polygon").attr('id'));
答案 1 :(得分:0)
我解决了!我做的是我将SVG加载到这个:https://jakearchibald.github.io/svgomg/并清理它并确保每个都在一行上。
然后我编写了一个脚本来打开这个svg文件,并将所有行重新格式化为JSON。
代码:
OpenFileDialog dlg = new OpenFileDialog();
dlg.DefaultExt = "*.csv";
dlg.Filter = "SVG Files (*.svg)|*.svg|All Files (*.*)|*.*";
DialogResult res = dlg.ShowDialog();
if (res == DialogResult.OK)
{
txtSource.Text = dlg.FileName; //Textbox to show filepath
}
using (StreamReader sr = new StreamReader(txtSource.Text.Trim(), Encoding.UTF8))
{
string line;
int ids = 1;
StringBuilder json = new StringBuilder();
json.Append("{\"Polygons\": [");
while ((line = sr.ReadLine()) != null)
{
string[] s = { };
string[] t = { };
string[] v = { };
StringBuilder test = new StringBuilder();
try
{
if (line.Trim().StartsWith("<poly"))
{
s = line.Split(new[] { "points=" }, StringSplitOptions.None);
t = s[1].Split('/');
string points = t[0].Replace("\"", "").Trim();
v = points.Split(' ');
foreach (string xy in v)
{
string[] z = { };
z = xy.Split(',');
test.Append("{\"x\":" + z[0].ToString() + ", \"y\":" + z[1].ToString() + "},");
}
//Found the polygon line
json.Append("{\"name\": \"polyId_" + ids + "\",");
json.Append("\"points\":[");
json.Append(test.ToString().TrimEnd(','));
json.Append("]},");
ids++;
}
}
catch { json.Append(line + " ERROR <br/>"); }
}
}
然后我将输出粘贴到.json文件中并加载它。然后我调整了我的d3脚本,只需获取d.name
svg.selectAll("polygon").on("mousemove", function (d) {
Ctooltip.attr("style", "left:420px;top:0px").html(d.name);
//console.log(d.name);
})
因此,最好的方法是避免使用从Illustrator导出的svg文件,但要将其转换为json并使用它。