如何在d3触摸事件中获得y坐标

时间:2018-02-05 14:50:32

标签: typescript d3.js ionic-framework interactive ontouchevent

我正在利用d3.js来显示我的Ionic应用程序中的数据。我有一个触摸事件,我用它来拖动一条线并获得其与我的图表的交点的坐标。我设法得到代表日期的x坐标,但我很难获得连续的y坐标。通过这个,我的意思是我能够通过循环数据数组找到对应于x坐标的离散y坐标,但我希望值“中间”。请看一下我尝试过的内容(一旦视图加载,我就调用函数drawChart()

private drawChart() {

    let width = 900 - this.margin.left - this.margin.right;
    let height = 500 - this.margin.top - this.margin.bottom;

    /*
        data is in the format: [{date: , value: }]
    */
    let data = this.data;

    let svg = d3.select("#chart")
    .append("svg")
    .attr("width", '100%')
    .attr("height", '100%')
    .attr('viewBox','0 0 900 500')
    .append("g")
    .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");

    let x = d3Scale.scaleTime().range([0, width]);
    let y = d3Scale.scaleLinear().range([height, 0]);
    x.domain(d3Array.extent(this.data, (d) => d.date ));
    y.domain(d3Array.extent(this.data, (d) => d.value ));

    svg.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate("0 + ", "+ height + ")")
        .call(d3Axis.axisBottom(x));

    svg.append("g")
        .attr("class", "axis axis--y")
        .call(d3Axis.axisLeft(y));

    let line: any = d3Shape.line()
    .x( (d: any) => x(d.date) )
    .y( (d: any) => y(d.value) );

    let path = g.append("path")
        .datum(this.data)
        .attr("class", "line")
        .attr("d", line);

    let cursorLine = svg
        .append("line")
        .attr("stroke-width",3)
        .attr("stroke","black")
        .style("opacity", 0);

    svg.on("touchstart", touched);
    svg.on("touchmove", touched);

    function touched() {

        let d = d3.touches(this);
        svg
        .selectAll("line")
        .data(d)
        .style("opacity", 1);

        svg
        .selectAll("line")
        .attr("x1", (d) => d[0])
        .attr("x2", (d) => d[0])
        .attr("y1", 0)
        .attr("y2", height);

        let formatTime = d3.timeFormat("%Y-%m-%d");
        let dateVal: string = formatTime(xScale.invert(d[0][0])); //x-coordinate of the cursor line
        let val = 0;

        //here, I can only get the y-value of the touch point/cursor line that is available in the data array
        //I need to get all the y-values continuously (not discrete) as I drag the cursor line
        data.forEach(d => {
           if(formatTime(d.date) === dateVal) {
               val = d.value;
            }
        })
    }
}

关于如何在拖动光标线时连续获取y值的任何想法?非常感谢!

1 个答案:

答案 0 :(得分:0)

也许你可以试试这个

let d = d3.touches(this);

如果你能通过这个获得x坐标

let dateVal: string = formatTime(xScale.invert(d[0][0])); //x-coordinate of the cursor line

你可以通过这个

获得y坐标
let dateVal2: string_y = y.invert(d[0][1]); //y-coordinate of the cursor line

d3.touches它可以d3.mouse.event console.log d gremlin console这必须包含y坐标