javascript - 原点引用错误

标签 javascript d3.js svg

将多个元素添加到 SVG 时,我遇到了原点错误的问题。

JSFiddle:https://jsfiddle.net/sbc6ejeu/2/

我添加了一个 SVG 和关联的路径以及几个圆圈。它们似乎对应于正确的起源。但是,当我移动 slider 时,我希望 id=movingCicle 的圆圈(如代码中所述)沿着绿色曲线(线)移动。我无法启动初始 圆的位置与其他 svg 元素同源。

我还观察到,红色圆圈的范围与其附加的其他元素或 SVG 不同。对于第二个和第三个下拉选项,当 slider 增加时,红色圆圈会移出图表。我觉得我错过了一些东西。

感谢对此的任何帮助。谢谢!

function initialize() {
  // Add circle data
  jsonCircles = [{
    "xAxis": 50,
    "yAxis": 154
  }, {
    "xAxis": 150,
    "yAxis": 154
  }];

  // Set the dimensions of the canvas / graph
  var margin = {
    top: 30,
    right: 20,
    bottom: 30,
    left: 50
  };
  width = 600 - margin.left - margin.right;
  height = 270 - margin.top - margin.bottom;

  // Set the ranges
  x = d3.scale.linear().range([0, width]);
  y = d3.scale.linear().range([height, 0]);

  // Define the axes
  xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(10);

  yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(7);

  valueLine = d3.svg.line()
    .x(function(d, i) {
      return x(i);
    })
    .y(function(d) {
      return y(d);
    });

  // Adds the svg canvas
  svg = d3.select("#graph")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .attr("id", "svg1")
    .append("g")
    .attr("transform",
      "translate(" + margin.left + "," + margin.top + ")");
}

function updateCirclePosition(i) {
  d3.select("#movingCircle").remove();

  svg.append("circle")
    .attr("cx", +i)
    .attr("cy", yValues[i])
    .attr("r", 5)
    .attr("id", "movingCircle")
    .style("fill", "red");
}

function addSvgElements() {
  // Add the valueline path.
  var path = svg.append("path")
    .attr("class", "line")
    .attr("id", "lineId")
    .attr("d", valueLine(yValues));
}

最佳答案

在函数updateCirclePosition中,变量i包含预算值,yValues[i]是相应的收入。

可以使用xy函数找到图表中相应的坐标,因此x(i)y( yValues[i]) 应用于设置正确的 cxcy:

svg.append("circle")
  .attr("cx", x(i))
  .attr("cy", y(yValues[i]))

更新了 fiddle :https://jsfiddle.net/sbc6ejeu/5/

关于javascript - 原点引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34923679/

相关文章:

html - 如何将 svg float 到背景大小为 : contain 的背景图像

javascript - 单击按钮时会打开新窗口,但使用 .onclick() 时不会打开新窗口

javascript - google caja 的使用方法

javascript - 如何将 React 的 getDerivedStateFromProps 与 setTimeout 一起使用?

javascript - 更改功能也会影响克隆 div

javascript - 将平行坐标库(d3.js)导入到jsfiddle

css - Svg 图标在 Chrome 和 Mozilla 浏览器中显示不同

javascript - 翻转 d3js svg 行

javascript - D3.js:圆形剪切路径不起作用?

javascript - D3 中的可重用函数