Answer the question
In order to leave comments, you need to log in
How to calculate the transformation of one object relative to another?
I'm trying to calculate the offset for a group of svg objects and put them over the original rectangle so that the group does not go beyond the size of the rectangle and is in the center, the parent of the group of elements and the rectangle is common.
And the original one is from what was already in the document, and I load the group of elements and insert it into the tree.
The scale was easy to calculate, but the transformations were put into a stupor, I just can’t achieve centering.
I give a code example.
<svg>
<g transform="translate(396.85,-130.759)">
<g transform="matrix(1,0,0,1,0,0)"></g>
<rect x="0" y="552.756" width="28.3465" height="42.5197" class="start-object"></rect>
<g transform="translate(51.0442,-37.0855)" class="transform-object">
<g transform="translate(47.0826,-46.7717)">
<rect x="0" y="167.4" width="14.1732" height="75.1181"></rect>
</g>
<g transform="translate(47.0826,0)">
<rect x="0" y="73.8569" width="14.1732" height="168.661"></rect>
</g>
<g transform="translate(271.884,151.101) rotate(90)">
<rect x="0" y="192.912" width="14.1732" height="49.6063"></rect>
</g>
</g>
</g>
</svg>
var startObj = $('.start-object'), // Объект тносительно которого будем выравнивать
tfmObj = $('.transform-object'), // Объект который будем выравнивать
svg = $('svg');
var tfmList = tfmObj[0].transform.baseVal, // трансформ лист смещаемого объекта
startObj = startObj[0].getBBox(),
tfmObjBBox = tfmObj[0].getBBox(),
scale = {},
tfmScale, tfmTranslate, startObjRect, tfmObjRect, offset;
scale.width = startObj.width / tfmObjBBox.width;
scale.height = startObj.height / tfmObjBBox.height;
scale.result = scale.height < scale.width ? scale.height : scale.width;
tfmScale = svg[0].createSVGTransform();
tfmScale.setScale(scale.result, scale.result);
tfmList.appendItem(tfmScale);
startObjRect = startObj[0].getBoundingClientRect();
tfmObjRect = tfmObj[0].getBoundingClientRect();
offset.x = pr.left - sr.left + (pr.width - sr.width) / 2;
offset.y = pr.top - sr.top + (pr.height - sr.height) / 2;
tfmTranslate = svg[0].createSVGTransform();
tfmTranslate.setTranslate(offset.x, offset.y);
tfmList.appendItem(tfmTranslate);
tfmList.consolidate();
html, body, svg{
width: 100%;
height: 100%;
}
body{
margin: 0;
}
.start-object{
fill: transparent;
stroke: red;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question