Zooming at the Mouse Coordinates with Affine Transformations

Ben Botto
6 min readMar 21, 2020

Providing zoom functionality in a graphical application is as simple as applying a scale matrix. If, however, the scale operation should occur at a specific point — about the user’s mouse location or about the center of the scene, for example — then some linear algebra and a handful of affine transformations can get the job done. In this article I’ll go over an algorithm for zooming at a point with some graphics for visual aid. There’s also some example JavaScript code that shows how to zoom using a 2D scene rendered in a canvas. The same algorithm works in 3D, but I’ve used a 2D scene in the example code for brevity and simplicity.

You can see an animated GIF of the code in action at the top of this article. To follow along, you should have the following in your tool belt.

  1. A basic understanding of linear algebra, including vectors, matrix multiplication, and translation and scale matrices.
  2. The ability to read JavaScript code. The zoom algorithm is generic — it will work with OpenGL, WebGL, DirectX, canvas, SVG, or whatever you use to render your scenes — but the demo code is written in JavaScript.

The Algorithm

Given a point P (for example, the coordinates of the mouse), zooming about that point using affine transformations is a four-step process.

  1. Apply any existing world-/scene-wide transformation(s). An existing world transformation might be a previous scale or pan…

--

--