ashokgct - 1 year ago 87

Javascript Question

I am doing a little project. In that one i need to resize the element such as ellipse which i had drawn. I know we can resize the ellipse by tracking down the mousemove property like this Example .

`function mouseMove(e) {}`

But i am curious to know how it works when we use

- Please explain how to use scale and transform property to resize the elements by tracking mouse move with an example?

Answer Source

Here is a basic example showing an ellipse changing size based on the mouse's current distance from the ellipse~~, without getting into matrices: https://jsfiddle.net/aaqs1wf0/~~: https://jsfiddle.net/aaqs1wf0/1/

SVG

```
<svg version="1.0" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 200 200" width="200px" height="200px">
<ellipse cx="100" cy="100" rx="20" ry="10"/>
</svg>
```

~~Javascript~~ (this contained unnecessarily adjusting of center, see update below)

```
var ellipse = document.getElementsByTagName("ellipse")[0];
var centerX = ellipse.getAttribute("cx");
var centerY = ellipse.getAttribute("cy");
window.addEventListener("mousemove", function(event) {
var x = event.clientX - centerX; // absolute distance from center
if (x<0) x = x * -1;
var y = event.clientY - centerY;
if (y<0) y = y * -1;
var scaleX = x/centerX; // proportional distance from center
var scaleY = y/centerY;
ellipse.setAttribute("cx", centerX/scaleX); // adjust the centers when adjusting scale so that it stays in one place.
ellipse.setAttribute("cy", centerY/scaleY);
ellipse.setAttribute("style","transform: scale(" + scaleX + ", " + scaleY + ")"); // scale the ellipse
});
```

**Updated JS** (which uses `transform-origin`

to set center, and `matrix()`

, as requested, though I think `scale()`

still works)

```
var ellipse = document.getElementsByTagName("ellipse")[0];
var centerX = ellipse.getAttribute("cx");
var centerY = ellipse.getAttribute("cy");
window.addEventListener("mousemove", function(event) {
var x = event.clientX - centerX; // absolute distance from center
if (x<0) x = x * -1;
var y = event.clientY - centerY;
if (y<0) y = y * -1;
var scaleX = x/centerX; // proportional distance from center
var scaleY = y/centerY;
ellipse.setAttribute("style","transform: matrix(" + scaleX + ",0,0, " + scaleY + ",0,0); transform-origin: 100px 100px;"); // scale the ellipse
});
```

Basically, it takes the mouse's coordinates, compares it to the coordinates of the center of the ellipse, then scales it to the proportional difference. Note that there's no built-in `function mouseMove()`

(like in your link), but rather a `mousemove`

event.