D3:从SVG检索数据 [英] D3 : Retrieve data from SVG

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

问题描述

是否可以通过d3从svg中检索数据?

Is it possible to retrieve data from an svg via d3?

我有以下场景:
在页面上调整大小我需要更新svg,它是通过d3在服务器上生成的。因此,例如x轴。但是客户端d3库没有svg的知识。我注意到,每个DOM对象都有一个__ chart__对象。

I have following scenario: on page Resize I need to update the widths of an svg which was generated on a server via d3 . So for example the x-axis. However the client side d3 library has no knowledge of the svg. I noticed that with each DOM object there is a __ chart__ object. Is there some way i can access the range and domain for example and update them accordingly?

推荐答案

当你创建一个SVG时,服务器并将其传输到客户端,则只会传输实际的SVG DOM,而不会传输您在创建它时使用的任何JavaScript对象或属性(例如d3 __ data __ 属性)。

When you create an SVG on the server and transfer it to the client, only the actual SVG DOM gets transferred, not any javascript objects or properties (such as the d3 __data__ property) that you used in creating it.

因此,为了将数据附加到实际通过文件传递的SVG元素,您需要创建包含数据的元素的属性。然后您可以选择元素客户端并解析数据属性。

So in order to attach data to the SVG elements that actually gets passed with the file, you would need to create an attribute of that element that contains the data. Then you can select the element client side and parse the data attribute.

示例:

/*** Server Side ***/
/* if `bars` is a d3 selection of rectangles in a bar graph */
bars.attr("data-name", function(d){return d.name;})
    .attr("data-value", function(d) {return d.value;});

/*** Client Side ***/
var bars = d3.selectAll("rect.bar")
             .datum(function(){
                return {
                  name: this.getAttribute("data-name"),
                  value: this.getAttribute("data-value")
                }
             })
             .on("click", function(d,i){
                 /* do something with the data */
             });

如果有问题的数据仅仅是几个要在工具提示中使用的数字或名称或类似的相互作用。它不适用于复杂的对象,如图表函数。如果你需要重绘/调整图表的客户端,我真的没有看到任何性能的好处,试图绘制服务器端的图。

That works if the data in question is simply a few numbers or names that you want to use in tooltips or similar interaction. It doesn't work for a complex object like a chart function. If you're need to redraw/resize the chart client-side, I really don't see any performance benefit in trying to draw the graphs server-side.

您可以创建服务器脚本来将所有数据解析为现成的格式,甚至可以运行d3布局函数来创建一个现成的JSON数组。但之后在客户端绘制图形。

You can create server scripts to parse all your data into a ready-to-use format, maybe even run the d3 layout functions to create a ready-to-draw JSON array. But then draw the graph client-side.

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

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