chartjs-plugin-zoom
chartjs-plugin-zoom copied to clipboard
[reactjs] zoom level state issue
I want to programatically close zoom ability
I have a variable
const [zoomLevel, setZoomLevel] = useState(0);
Use it like this
const zoomOptions = useMemo(() => ({
pan: {
enabled: true,
mode: 'xy',
modifierKey: 'alt'
},
zoom: {
mode: 'xy',
drag: {
enabled: true,
borderColor: 'rgb(54, 162, 235)',
borderWidth: 1,
backgroundColor: 'rgba(54, 162, 235, 0.3)'
},
onZoom: ({}) => {
console.log("ZOOM LEVEL", zoomLevel)
setZoomLevel(prevState => prevState + 1);
},
onZoomStart: ({}) => {
console.log("ZOOM START", zoomLevel)
if (zoomLevel >= 8) {
console.log("FORBID!")
return false;
}
}
}
}), [zoomLevel]);
And zoom stops working almost immediately. What am I doing wrong?
You can use the getZoomLevel
API call to get the zoom level so you dont need to keep your own state:
https://stackblitz.com/edit/react-ts-1vewrp?file=Chart.js
@LeeLenaleee thank you, but it gives me weird numbers:
ZOOM START 3.15 ZOOM START 11.31
What do they mean, why the are not like, you know, once selected zoom level = 1, selected on selected (twice) zoom level = 2 and so on etc. It'll be very plain to see and handle.
And I also want to have my own state variable to show a zoom out button only when user zoomed at least once, so I still want to set and have an access to zoom state variable inside the onZoomStart function. Currently it could not read updated values, I wonder why?
onZoomStart: ({}) => {
console.log("ZOOM START", zoomLevel)
if (zoomLevel >= 8) {
console.log("FORBID!")
return false;
}
}
here it always says zoomLevel = 0
Those are the real zoom values, so that a zoomLevel of 8 is always consistent and the same, in your solution if someone zooms 7 times by selecting almost the whole chartArea they can't zoom any further while someone else that selects 2 pixels can zoom 6 more times.
@LeeLenaleee, @vtarelkin How to get boundaries(here boundaries as in min and max value for x and y for particular zoom) onZoom?
If im correct you get the chart object in your onZoom callback, here you can call chart.scales[scaleId].min
and chart.scales[scaleId].max
if im correct (cant test atm but verry sure this should work)
If im correct you get the chart object in your onZoom callback, here you can call
chart.scales[scaleId].min
andchart.scales[scaleId].max
if im correct (cant test atm but verry sure this should work)
It worked thank you : )