ChartJS zoom очень неточно с chartjs-plugin-zoom

Я пытаюсь реализовать поиск с помощью перетаскивания, поскольку версия с колесиком кнопки очень медленная, но, похоже, она не работает должным образом

Я реализовал в соответствии с документами:

zoom: {
  enabled: true,
  drag: true,
  mode: 'x'
}

Я добавил фрагмент кода.

Кто-нибудь реализовал это для работы с использованием метода перетаскивания?

window.chartColors = {
  red: "rgb(255, 99, 132)",
  orange: "rgb(255, 159, 64)",
  yellow: "rgb(255, 205, 86)",
  green: "rgb(75, 192, 192)",
  blue: "rgb(54, 162, 235)",
  purple: "rgb(153, 102, 255)",
  grey: "rgb(201, 203, 207)"
};

var Months = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];

var COLORS = [
  "#4dc9f6",
  "#f67019",
  "#f53794",
  "#537bc4",
  "#acc236",
  "#166a8f",
  "#00a950",
  "#58595b",
  "#8549ba"
];

var Samples = Samples || (Samples = {});
var Color = Color;

Samples.utils = {
  // Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
  srand: function(seed) {
    this._seed = seed;
  },

  rand: function(min, max) {
    var seed = this._seed;
    min = min === undefined ? 0 : min;
    max = max === undefined ? 1 : max;
    this._seed = (seed * 9301 + 49297) % 233280;
    return min + this._seed / 233280 * (max - min);
  },

  numbers: function(config) {
    var cfg = config || {};
    var min = cfg.min || 0;
    var max = cfg.max || 1;
    var from = cfg.from || [];
    var count = cfg.count || 8;
    var decimals = cfg.decimals || 8;
    var continuity = cfg.continuity || 1;
    var dfactor = Math.pow(10, decimals) || 0;
    var data = [];
    var i, value;

    for (i = 0; i < count; ++i) {
      value = (from[i] || 0) + this.rand(min, max);
      if (this.rand() <= continuity) {
        data.push(Math.round(dfactor * value) / dfactor);
      } else {
        data.push(null);
      }
    }

    return data;
  },

  labels: function(config) {
    var cfg = config || {};
    var min = cfg.min || 0;
    var max = cfg.max || 100;
    var count = cfg.count || 8;
    var step = (max - min) / count;
    var decimals = cfg.decimals || 8;
    var dfactor = Math.pow(10, decimals) || 0;
    var prefix = cfg.prefix || "";
    var values = [];
    var i;

    for (i = min; i < max; i += step) {
      values.push(prefix + Math.round(dfactor * i) / dfactor);
    }

    return values;
  },

  months: function(config) {
    var cfg = config || {};
    var count = cfg.count || 12;
    var section = cfg.section;
    var values = [];
    var i, value;

    for (i = 0; i < count; ++i) {
      value = Months[Math.ceil(i) % 12];
      values.push(value.substring(0, section));
    }

    return values;
  },

  color: function(index) {
    return COLORS[index % COLORS.length];
  },

  transparentize: function(color, opacity) {
    var alpha = opacity === undefined ? 0.5 : 1 - opacity;
    return Color(color)
      .alpha(alpha)
      .rgbString();
  }
};

// DEPRECATED
window.randomScalingFactor = function() {
  return Math.round(Samples.utils.rand(0, 100));
};

// INITIALIZATION

Samples.utils.srand(Date.now());

function createData(year, color) {
  return {
    label: year,
    backgroundColor: window.chartColors[color],
    borderColor: window.chartColors[color],
    data: [
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor(),
      randomScalingFactor()
    ],
    fill: false
  };
}

var MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
var config = {
  type: "line",
  data: {
    labels: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    ],
    datasets: [
      createData("2014", "yellow"),
      createData("2015", "red"),
      createData("2016", "green"),
      createData("2017", "orange"),
      createData("2018", "purple"),
      createData("2019", "grey")
    ]
  },
  options: {
    responsive: true,
    maintainAspectRatio: true,
    legend: {
      display: false
    },
    title: {
      display: true,
      text: "Paris Rainfall",
      fontSize: 20
    },
    tooltips: {
      //mode: 'index',
      intersect: true
    },
    hover: {
      mode: "nearest",
      intersect: true
    },
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: "Month",
          fontStyle: "bold",
          fontSize: 20
        }
      }],
      yAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: "Amount (mm)",
          fontStyle: "bold",
          fontSize: 20
        }
      }]
    },
    zoom: {
      enabled: true,
      drag: true,
      mode: 'x'
    }
  }
};

window.handleClick = function(e) {
  var index = $(this).index();
  $(this).toggleClass("dim");
  var curr = window.myLine.data.datasets[index];
  curr.hidden = !curr.hidden;
  window.myLine.update();
};

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  window.myLine = new Chart(ctx, config);
  $("#chartjs-legend").append(myLine.generateLegend());
  $("#chartjs-legend > ul > li")
    .off()
    .on("click", handleClick);
  $('#chartjs-legend').css({
    'top': '20px',
    'left': '90%'
  });
};

document.getElementById("randomizeData").addEventListener("click", function() {
  config.data.datasets.forEach(function(dataset) {
    dataset.data = dataset.data.map(function() {
      return randomScalingFactor();
    });
  });
  myLine.update();
});

var colorNames = Object.keys(window.chartColors);
document.getElementById("addDataset").addEventListener("click", function() {
  var colorName = colorNames[config.data.datasets.length % colorNames.length];
  var newColor = window.chartColors[colorName];
  var newDataset = {
    label: "Dataset " + config.data.datasets.length,
    backgroundColor: newColor,
    borderColor: newColor,
    data: [],
    fill: false
  };

  for (var index = 0; index < config.data.labels.length; ++index) {
    newDataset.data.push(randomScalingFactor());
  }

  config.data.datasets.push(newDataset);
  myLine.update();
  $("#chartjs-legend").html('<p>Legend</p>' + window.myLine.generateLegend());
  $("#chartjs-legend > ul > li")
    .off()
    .on("click", handleClick);
});

document.getElementById("addData").addEventListener("click", function() {
  if (config.data.datasets.length > 0) {
    var month = MONTHS[config.data.labels.length % MONTHS.length];
    config.data.labels.push(month);

    config.data.datasets.forEach(function(dataset) {
      dataset.data.push(randomScalingFactor());
    });

    myLine.update();
  }
});

document.getElementById("removeDataset").addEventListener("click", function() {
  config.data.datasets.splice(0, 1);
  myLine.update();
  $("#chartjs-legend").html('Legend' + window.myLine.generateLegend());
});

document.getElementById("removeData").addEventListener("click", function() {
  config.data.labels.splice(-1, 1); // remove the label first

  config.data.datasets.forEach(function(dataset) {
    dataset.data.pop();
  });

  myLine.update();
  $("#chartjs-legend").append(window.myLine.generateLegend());
});

document.getElementById("zoomReset").onclick = function() {
  console.log("click");
  myLine.resetZoom();
};
$(window).resize(() => {
  var canvas = document.getElementById('canvas');
  var canvas = document.getElementById('canvas');
  var width = canvas.width;
  var height = canvas.height;
  console.log(height);
  $('#chartjs-legend').css({
    'maxHeight': (height - 70) + 'px',
    'top': '20px',
    'left': (width - ((width / 10) * 4)) + 'px'
  });
});

//Make the DIV element draggagle:
dragElement(document.getElementById(("chartjs-legend")));

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
.outer {
  display: inline-block;
  width: 100%;
  clear: both;
  margin-bottom: 60px;
  position: relative;
}

.outer .chart-legend li span {
  display: inline-block;
  width: 12px;
  height: 12px;
  margin-right: 5px;
}

.outer #chartjs-legend {
  position: absolute;
  overflow-y: auto;
  padding: 8px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #ccc;
  margin: 0;
  border-radius: 4px;
  box-shadow: 3px 4px 8px 0px #cccccc;
}

.outer #chartjs-legend p {
  cursor: move;
  margin: 0;
  background: #eee;
  padding: 6px 4px;
  user-select: none;
  border-radius: 2px;
  font-family: 'Arial';
}

.outer #chartjs-legend ul {
  clear: both;
  max-height: 350px;
  list-style-type: none;
  padding: 0;
}

.outer #chartjs-legend ul li {
  cursor: pointer;
  border-bottom: 1px solid transparent;
  border-top: 1px solid transparent;
}

.outer #chartjs-legend ul li:hover {
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
}

.outer #chartjs-legend ul .dim {
  opacity: 0.3;
}

.outer #chartjs-legend ul .float-left {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/0.6.3/chartjs-plugin-zoom.min.js"></script>

<button id="zoomReset">reset zoom</button>
<div class="outer">
  <canvas id="canvas"></canvas>
  <div id="chartjs-legend" class="chart-legend">
    <p>Legend</p>
  </div>
</div>

<div class="outer">

  <button id="randomizeData">Randomize Data</button>
  <button id="addDataset">Add Dataset</button>
  <button id="removeDataset">Remove Dataset</button>
  <button id="addData">Add Data</button>
  <button id="removeData">Remove Data</button>
</div>

0 ответов

Другие вопросы по тегам