如何使SVG / D3js可点击并获取值?

时间:2015-06-02 13:33:03

标签: javascript svg

这是我的整个JS代码,我真的只是基于一些例子开始。

我希望能够捕捉到整个绘图上的点击事件,然后在图表行上找到它并获得y值。

onMouseOver和onMouseOut目前正在按预期工作。

谢谢。

//Example may be interesting: http://bl.ocks.org/byrongibson/5232838

var parseDate = d3.time.format("%d-%b-%y").parse;
var svg, d3, x, y, valueline, xAxis, yAxis, width, height;

function CreateSvg()
{
    // 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.time.scale().range([0, width]);
    y = d3.scale.linear().range([height, 0]);

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

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

    // Define the line
    valueline = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.close); });

    //var rect = d3.selectAll("rect");

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

function GetData(data)
{
    data.forEach(function(d)
    {
        d.date = parseDate(d.date);
        d.close = +d.close;
    });
    data.reverse();
    data.push({date:parseDate('3-May-12'), close:Math.random() * 1200});
    data.push({date:parseDate('4-May-12'), close:Math.random() * 1200});
    data.reverse();
    return data;
}

function Draw()
{
    d3.csv("data.csv", function(error, data) {
    data = GetData(data);

    // Scale the range of the data
    x.domain(d3.extent(data, function(d) { return d.date; }));
    y.domain([0, d3.max(data, function(d) { return d.close; })]);

    svg.text("");

    // Add the valueline path.
    svg.append("path")  
        .attr("class", "line")
        .attr("d", valueline(data))
        .on("mouseover", onMouseOver)
        .on("mouseout", onMouseOut)
        .on("click", click)
        ;

    // Add the X Axis
    svg.append("g")     
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    // Add the Y Axis
    svg.append("g")     
        .attr("class", "y axis")
        .call(yAxis);
});
}

function click() {
    alert("onclick");
}

function onMouseOver(){
    alert("mouseOver");
};

function onMouseOut(){
    alert("mouseOut");
};

CreateSvg();    
Draw();
Draw();

0 个答案:

没有答案
相关问题