chartjs / chartjs-plugin-zoom

Zoom and pan plugin for Chart.js
MIT License
598 stars 327 forks source link

Logarithmic Zooming with mousewheel not centered #821

Closed amosmatter closed 2 weeks ago

amosmatter commented 4 months ago

When Zooming with the mouswheel, the Zoom center is not where the mouse is if the scale is logarithmic. To fix this, the values would need to be mapped to a logarithmic scale before applying zoomdelta and back to exponential after. I created a small workaround which seems to work in my usecase:

    zoomPlugin.zoomFunctions.logarithmic = (scale, zoom, center, limits) => {
    const {id, axis, options: scaleOpts} = scale;

    const centerPoint = scale.isHorizontal() ? center.x : center.y;

    const val = scale.getValueForPixel(centerPoint)
    if (val === undefined) {
      return true;
    }

    const logmin = Math.log10(scale.min);
    const logmax = Math.log10(scale.max);
    const logval = Math.log10(val);

    const range = logmax - logmin;
    const zoomRange = range * (zoom - 1);

    const minPercent = Math.max(0, Math.min(1, (logval - logmin) / range || 0));
    const maxPercent = 1 - minPercent;

    const newlogmin = minPercent * zoomRange;
    const newlogmax = maxPercent * zoomRange;

    scaleOpts.min = Math.pow(10, logmin + newlogmin);
    scaleOpts.max = Math.pow(10, logmax - newlogmax);
    return false;
    };
kurkle commented 2 weeks ago

Would you be willing to make a pull request for this?