I have this react project. The person who developed created zoom function like this:
MouseWheelHandler(e) {
if (e.ctrlKey === true) {
// Disable default page zoom
e.preventDefault();
}
var scroll, canvasWidth, canvasHeight;
if (e.deltaY < 0) {
this.props.dispatch(mainActions.updateImage(true));
this.props.dispatch(mainActions.setMouseActive(true));
if (this.props.zoomScale < maxZoom) {
scroll = this.props.zoomScale + 1;
canvasWidth = this.props.canvasWidth + canvasZoomWidth;
// canvasHeight = this.props.canvasHeight + canvasZoomHeight
canvasHeight = canvasWidth/this.props.originalImageWidth * this.props.originalImageHeight;
}
else {
scroll = this.props.zoomScale;
canvasWidth = this.props.canvasWidth;
canvasHeight = this.props.canvasHeight;
}
}
else {
this.props.dispatch(mainActions.updateImage(true));
this.props.dispatch(mainActions.setMouseActive(true));
if (this.props.zoomScale > 0) {
scroll = this.props.zoomScale - 1;
canvasWidth = this.props.canvasWidth - canvasZoomWidth;
// canvasHeight = this.props.canvasHeight - canvasZoomHeight
canvasHeight = canvasWidth/this.props.originalImageWidth * this.props.originalImageHeight;
}
else {
scroll = this.props.zoomScale;
canvasWidth = this.props.canvasWidth;
canvasHeight = this.props.canvasHeight;
}
}
this.props.dispatch(mainActions.updateZoomScale(
{
zoomScale: scroll,
canvasWidth: canvasWidth,
canvasHeight: canvasHeight
}));
}
So it changes canvas size when wheel is scrolled.
However, when zoomed it ends up the at top left corner of the image.
I tried to add a translation logic this way:
componentDidUpdate(prevProps) {
if (prevProps.canvasWidth !== this.props.canvasWidth || prevProps.canvasHeight !== this.props.canvasHeight) {
this.updateCanvas();
}
}
updateCanvas() {
console.log('Update canvas');
const canvas = ReactDOM.findDOMNode(this.refs.canvas);
const ctx = canvas.getContext("2d");
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Apply transformations
ctx.save();
ctx.translate(this.props.canvasWidth / 2, this.props.canvasHeight / 2);
ctx.restore();
}
But it doesn’t work. Update canvas runs but canvas doesn’t have any changes.
P.S: Can anyone tell me why is this happening. I am new to this and someone else developed the project.
I want to be able to zoom in the image where my mouse pointer is placed.