
We defined our anchor point, next all we need to do is to define all of our coordinates relative to this anchor point (and in this case relative to the top left corner of the shape's bbox). Have another look at the ilustration and the demo and check how the anchor and the bbox behave. If you're confused at this point, don't worry. We call this the bounding box (or bbox for short). The red box around the triangle shows the space the triangle takes up. So the x coordinate is equal to the point of the triangle that's the furthest left and the y coordinate is equal to the point that's furthest on top. We'll place the anchor opposite to where our mouse cursor is.


To do this we'll create a new point and we'll call this point the anchor. Notice how the left side of the triangle also moves? We want to move the triangle in relation to itself, not in relation to the entire coordinate system So when our shape is not at the origin (0 / 0) of the coordinate system, this happens: Our coordinates are defined in relation to the entire coordinate system. If we multiply both by 2 we get the new point x = 2, y = 0.ĭo that with every point and you scaled your element to twice the size! Making it relative The top point starts with the coordinates x = 1, y = 0. We call this number the "growth factor" (or growth rate). So If we want a triangle twice the size we take the x and y of each point and multiply by 2. To scale our triangle we need to multiply each point by the same factor. I use SVG (which has an actual coordinate system) but you can also turn your new coordinates back into width / height values after doing the math.įor our example, we can define our shape with 3 points.

The specific implementation for this doesn't matter. It's also easy to extend with features like resizing multiple elements at the same time or preserving the aspect ratio of a box.

This article shows such an approach and all the edge cases that arise from it.īy doing it in a mathematical way we avoid most of the edge cases and end up with code that's easier to read/debug. If you forgot how coordinate systems work, here's a 6 minute catch up.Ī common approach to resizing is to try to change the width or height of an element directly. Let's start by establishing a coordinate system. I wrote the example in Svelte but if you know Vue or React you should be able to read it.
