基于关键SVG数据绑定 [英] SVG databinding based on key

查看:932
本文介绍了基于关键SVG数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有象下面这样的SVG

I have an svg like below

<g>
   <path d="M150 0 L75 200 L225 200 Z" id='path1'/>
   <path d="M151 0 L75 200 L225 100 Z" id='path2'/>
   <path d="M152 0 L75 200 L225 300 Z" id='path3'/>
   <path d="M153 0 L75 200 L225 400 Z" id='path4'/>
</g>

和我有一个像

{
    [
      "path2",
      "22218",
      "26627",
      "29101"
    ],
    [
      "path4",
      "218",
      "207",
      "160"
    ]
    [
      "path3",
      "22218",
      "26627",
      "29101"
    ],
    [
      "path1",
      "218",
      "207",
      "160"
    ]
}

我很困惑如何结合基于所述key.I我假设我可以每个阵列作为数据密钥中使用的第一个元素的数据。但我怎么使用它在。数据()功能?

有什么建议?

推荐答案

首先,你要分配哑数据添加到已有的元素,基于该元素的某些属性(在这种情况下,ID使用属性) selection.datum 。您分配应该把标识符,你会与实际输入数据使用相同格式的数据(在这种情况下,数组的索引0是标识符):

First, you'll want to assign 'dummy' data to the existing elements, based on some attribute of that element (in this case, the 'id' attribute) using selection.datum. The data you assign should put the identifier in the same format you'll be using with your actual input data (in this case, index 0 of the array is the identifier):

var paths = d3.selectAll("path")
    .datum(function(d) { return [d3.select(this).attr("id")]; })

然后,您可以将数据以这些路径,并使用一键功能,按通常:

Then, you can assign data to these paths, and use a key function, as per usual:

    .data(data, function(d) { return d[0]; });

要测试,可以打印到控制台:

To test, you can print to the console:

paths.each(function(d) { console.log(this, d); });

在这种情况下,输出:

which in this case, outputs:

<path id="path2" d="M151 0 L75 200 L225 100 Z"> ["path2", "22218", "26627","29101"]
<path id="path4" d="M153 0 L75 200 L225 400 Z"> ["path4", "218", "207", "160"]
<path id="path3" d="M152 0 L75 200 L225 300 Z"> ["path3", "22218", "26627", "29101"]
<path id="path1" d="M150 0 L75 200 L225 200 Z"> ["path1", "218", "207", "160"]

这里。

这篇关于基于关键SVG数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆