Plotly_click在图

时间:2018-04-20 14:55:42

标签: javascript click plotly

我已经实现了Plotly.js create a point on click中提到的Plotly onclick-method的代码,但在我的PC上,click方法并不完美。问题是,如果我点击图表,e.layerXe.layerY会返回0。 move方法中的代码完美无缺,尽管它与click方法几乎完全相同。 这是我的代码:

var maxXGraph = 24;
var maxYGraph = 36;

var touchobj;
var lastTouchDownXY = [0, 0];

var xValueArray = ['0.25', '12.25', '22.23'];
var yValueArray = [1, 3, 35];

var data = [ {
    x: xValueArray,
    y: yValueArray,
    type: 'scatter'
}];

var layout = {
    hovermode: 'closest',
  xaxis: {
    autorange: true,
    range: [0, maxXGraph],
    type: 'linear'
  },
  yaxis: {
    autorange: true,
    range: [0, maxYGraph],
    type: 'linear'
 }
};

Plotly.newPlot('myChart', data, layout);
var graph = document.getElementById('myChart');

Number.prototype.between = function(min, max) {
  return this >= min && this <= max;
};

Plotly.d3.select(".plotly").on('click', function(d, i) {
    var e = Plotly.d3.event;
    var bg = document.getElementsByClassName('bg')[0];
    alert(e.layerX);    //returns 0 on graph
    alert(e.layerY);    //returns 0 on graph
    var x = ((e.layerX - bg.attributes['x'].value + 4)/
    (bg.attributes['width'].value)) * (graph.layout.xaxis.range[1] -
    graph.layout.xaxis.range[0]) + graph.layout.xaxis.range[0];
    var y = ((e.layerY - bg.attributes['y'].value + 4) / 
    (bg.attributes['height'].value)) * (graph.layout.yaxis.range[0] -
    graph.layout.yaxis.range[1]) + graph.layout.yaxis.range[1];

    if (x.between(graph.layout.xaxis.range[0], 
        graph.layout.xaxis.range[1]) &&
        y.between(graph.layout.yaxis.range[0], 
        graph.layout.yaxis.range[1])) {
         xValueArray.push(x);
         yValueArray.push(y);
   }

   data = [ {
      x: xValueArray,
      y: yValueArray,
      type: 'scatter'
   }];
   Plotly.newPlot('myChart', data, layout);
});

Plotly.d3.select(".plotly").on('mousemove', function(d, i) {
  var e = Plotly.d3.event;
  var bg = document.getElementsByClassName('bg')[0];

  var x = ((e.layerX - bg.attributes['x'].value + 4) / 
  (bg.attributes['width'].value)) * (graph.layout.xaxis.range[1] -
  graph.layout.xaxis.range[0]) + graph.layout.xaxis.range[0];
  var y = ((e.layerY - bg.attributes['y'].value + 4) / 
  (bg.attributes['height'].value)) * (graph.layout.yaxis.range[0] - 
  graph.layout.yaxis.range[1]) + graph.layout.yaxis.range[1];

  if (x.between(graph.layout.xaxis.range[0], graph.layout.xaxis.range[1])
  && y.between(graph.layout.yaxis.range[0], graph.layout.yaxis.range[1]))    
  {
     console.log("Location X:"+x+" Y"+y)
     document.getElementById("xvalue").value = x;
     document.getElementById("yvalue").value = y;
  }
});

让任何人有更好的相同问题或事件,解决方案。

提前谢谢

0 个答案:

没有答案