Chartjs-Control Scaling of Canvas When dragged out of chart limit

0๐Ÿ‘

โœ…

If a dragStart event occurs beyond the scale limits, the increment should be a fixed value to avoid the issue you mentioned. Also, ticks.min and ticks.max should be set for the same purpose. Below is a sample jsfiddle and code (you can control speed by step).

https://jsfiddle.net/oLrk3fb2/

function onDragStart() {
  const event = d3.event.sourceEvent;
  const scales = chartInstance.scales;
  const scaleInstanceY = scales[scaleY];
  const scaleInstanceX = scales[scaleX];
  const scalesOpts = chartInstance.options.scales;
  const ticksOptsX = scalesOpts.xAxes[0].ticks;
  const ticksOptsY = scalesOpts.yAxes[0].ticks;
  const step = 1;

  datasetIndex = element['_datasetIndex'];
  index = element['_index'];
  valueY = scaleInstanceY.getValueForPixel(event.offsetY);
  valueX = scaleInstanceX.getValueForPixel(event.offsetX);

  if (valueY < scaleInstanceY.min) {
    ticksOptsY.min = valueY = scaleInstanceY.min - step;
  }
  if (valueY > scaleInstanceY.max) {
    ticksOptsY.max = valueY = scaleInstanceY.max + step;
  }
  if (valueX < scaleInstanceX.min) {
    ticksOptsX.min = valueX = scaleInstanceX.min - step;
  }
  if (valueX > scaleInstanceX.max) {
    ticksOptsX.max = valueX = scaleInstanceX.max + step;
  }

  chartInstance.data.datasets[datasetIndex].data[index] = {
    x: valueX,
    y: valueY
  }
  chartInstance.update(0);
}

Leave a comment