This article mainly introduces a way to achieve canvas scaling by setting the canvas's transformation matrix.
The first step is to listen to the mouse wheel event. In the wheel event, based on the scrolling of the mouse and the previous transformation, the zoom and translation of the context are reset. The core code is as follows:
let delta = this.deltaInst; delta.bind('zoom', (data) => { delta._transform.scale.forEach((s, i) => { delta._transform.scale[i] *= data.delta > 0? 2 : 1/2; }); let offsetX = data.x - delta._transform.translate[0]; let offsetY = data.y - delta._transform.translate[1]; delta._transform.translate[0] += -(data.delta > 0? 1 : -1/2)*offsetX; delta._transform.translate[1] -= (data. delta > 0? 1 : -1/2)*offsetY; delta.refreshAll();});
It is assumed here that each zoom is magnified by 2 times, but it can also be other zoom ratios.
The first step is to multiply or divide the current zoom ratio by 2 according to the direction of scrolling;
The second step is to calculate the translation. The basic idea is to calculate the position where the canvas can be translated to achieve the same effect when scaling the point on the canvas to the center position based on the new mouse position.
Let’s take a look at the refreshAll code:
let ctx = this.context; let matrix = this.getTransformMatrix(); ctx.save(); ctx.transform(...matrix); //ctx.translate(...this._transform.translate); // ctx.scale(...this._transform.scale); if (!Array.isArray(shapes)) { shapes = [shapes]; } shapes.forEach( (shape) => { shape.render(ctx); }); ctx.restore();
The code first obtains a change matrix based on the scale value scale and translation value calculated previously, and then passes the corresponding value in the matrix to the transform method of the context, performs a given transformation on the canvas, and then performs the previous scaling completely Consistent drawing operations will produce the same effect as after scaling~~
In the above code, ctx.transform() can also be completely replaced by the ctx.translate() and ctx.scale() methods. As shown in the comment part of the code, the parameters are the values calculated previously.
The complete code can be found at github address: https://github.com/helloweilei/delta
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.