2016-01-21 49 views
2

當多個元素添加到一個SVG我現在面臨的問題與錯誤的起始點。錯點的原點參考

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

我添加圓的SVG和關聯的路徑,並連接到它。他們似乎對應於正確的來源。然而,當我移動滑塊時,我期望ID = movingCicle(如在代碼中提到)的圓沿着綠色曲線(線)移動。我無法啓動循環的初始 位置相同的起源其他SVG元素。

此外,我觀察到與其他元件或SVG其所所附紅色圓圈的範圍是不相同的。對於第二個和第三個下拉選項,當滑塊增加時,紅色粒子移出圖表。我覺得我錯過了某些東西。

Appretiate上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)); 
} 
+0

這是相當難以理解當我移動滑塊時應該發生什麼 - 它應該將紅點移動到右邊,還是應該沿着綠色路徑或?它應該做什麼? – tiblu

+0

@tiblu它應該沿綠線移動。我已將此預期行爲添加到描述 – Srikanta

回答

3

功能updateCirclePosition內部,變量i包含的預算值,而yValues[i]是相應的收入。

圖表中的相應座標可以使用xy功能,因此x(i)y(yValues[i])發現應該用來設置正確的cxcy

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

更新小提琴:https://jsfiddle.net/sbc6ejeu/5/

+0

感謝您解釋使用函數將值分配給cx&cy。 – Srikanta