T
T
thehighhomie2018-05-28 19:52:05
JavaScript
thehighhomie, 2018-05-28 19:52:05

Mathematical calculations for adaptive scaling of an element with ancestors in JS?

I am writing an application that should be able to scale elements, as for example in Photoshop: there is a container, in an indefinite number of elements, which, when the container is reduced / enlarged, should adaptably decrease / increase along with it, for example, as on the canva.com service, when you reduce the presentation Or you increase that elements should be adjusted.
Since all this should work on js, adaptive layout does not roll)
From reflections, I came to the following:
Elements should only change sizes (width, height, taking into account the aspect ratio).
No offset is needed either (top, left, translateX / Y) I
wrote the code for changing the size of the element (only to reduce it):

let width = this.container.clientWidth;
let scalePercent = (this.maxWidth - width) * 100 / this.maxWidth; // this.maxWidth - это изначальная ширина контейнера, самая большая.
let elemWidth = this.container.clientWidth - (scalePercent * 100 / this.container.clientWidth);
let height = (width * this.aspectRatio / 100);
elemstyle.height = height + 'px';
elem.style.width = width + 'px';

In general, I calculate a percentage from the width of the container - the current width of the container, then from this percentage I get the desired width for the element. Well, I put the height in proportion to the width.
And it doesn't work right. Elements are reduced very quickly, to dots ...
Tell me a working method please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Griboks, 2018-05-28
@thehighhomie

Wrote the code for changing the size of the element

I don't understand where it came from. Therefore, I propose my own algorithm:
let scale = newContainerWidth/oldContainerWidth;
element.width*=scale;
element.containerRelativePosition.x*=scale;

V
Vitaly, 2018-05-28
@rim89

Since all this should work on js, adaptive layout does not roll)

what does js mean? JS you can write logic, but it will be displayed anyway in html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question