Srikanta
Srikanta

Reputation: 1147

Wrong point of origin reference

I'm facing problem with wrong point of origin when multiple elements are added to an SVG.

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

I've added an SVG and associated path and couple of circles to it. They seem to correspond to the correct origin. However when I move the slider, I expect the circle of id=movingCicle (as mentioned in the code) to move along the green curve (line). I'm unable to start the initial position of the circle to the same origin as other svg elements.

Also I observe that the range of the red circle is not same as the other elements or the SVG to which it is appended. For the 2nd and 3rd drop down options, the red cicle moves out of the graph when the slider is increased. I feel I'm missing out on something.

Appretiate any help on this.Thanks!

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));
}

Upvotes: 2

Views: 52

Answers (1)

Mehdi
Mehdi

Reputation: 7403

Inside the function updateCirclePosition, the variable i contains the value of the budget, and yValues[i] is the corresponding revenue.

The corresponding coordinates in the chart can be found using x and y functions, therefore x(i) and y(yValues[i]) should be used to set the correct cx and cy:

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

updated fiddle: https://jsfiddle.net/sbc6ejeu/5/

Upvotes: 3

Related Questions