如何使用d3从json文件中读取路径信息

时间:2015-04-27 19:07:57

标签: javascript json d3.js

我正在从形状json文件中读取形状信息并使用d3将它们可视化。

我让它适用于矩形。我需要一些帮助来阅读路径信息。

我如何阅读路径?我应该以不同方式组织我的json文件吗?

d3.json("shapes.json", function(json) {
  /* Define the data for the circles */
  var elem = svgContainer3.selectAll("g")
    .data(json.rooms)

  /*Create and place the "blocks" containing the rooms and the text */
  var elemEnter = elem.enter()
    .append("g")
    .attr("transform", function(d) {
      return "translate(0,0)"
    })

  /*Create the rooms for each block */
  var room = elemEnter.append("rect")
    .attr("width", function(d) {
      return d.w
    })
    .attr("height", function(d) {
      return d.h
    })
    .attr("x", function(d) {
      return d.x
    })
    .attr("y", function(d) {
      return d.y
    })
    .attr("stroke", "black")
    .attr("fill", "white")

  /* Create the text for each room */
  elemEnter.append("text")
    .attr("x", function(d){return d.x})
    .attr("y", function(d){return d.y})
    .attr("dx", function(d){return 15})
    .attr("dy", function(d){return 15})
    .text(function(d) {
      return d.label
    })

/// Read for Path

带有矩形和路径文件的JSON文件。

{"rooms":[
  {"w":50, "h":30, "x":125 , "y":240, "label":"200"}, 
  {"w":70, "h":30, "x":175 , "y":240, "label":"202"},
  {"w":30, "h":30, "x":245 , "y":240, "label":""},
  {"w":70, "h":30, "x":275 , "y":240,"label":"204"},
  {"w":50, "h":30, "x":345 , "y":240,"label":"206"}
],
"paths":[
    {"lineData":[
        {"x": 1,"y": 5},
        {"x": 20,"y": 5},
        {"x": 20,"y": 20},
        {"x": 1,"y": 20},
        {"x": 1,"y": 5}
    ], "label":"222"}, 
    {"lineData":[
        {"x": 20,"y": 5},
        {"x": 40,"y": 5},
        {"x": 40,"y": 20},
        {"x": 20,"y": 20},
        {"x": 1,"y": 5}
    ],"label":"220"}
]}

1 个答案:

答案 0 :(得分:0)

我想我可能在经过一些实验后回答了我自己的问题。

   // create a selection to bind the data to
  var paths = svgContainer3.selectAll('paths')
    // bind the incoming data
    .data(json.paths)
   // for each incoming datapoint...
   .enter()
    // append a path element...
    .append('svg:path')
    // giving it a pathdata attribute corresponding to the current element in the data array
    .attr('d', function(d) { 
      d = lineFunctionStep(d.lineData)
      return d; })
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .attr("fill", "none");