JSFiddle - React, Tailwind, and code Playground
HTML
<svg xmlns="http://www.w3.org/2000/svg" viewBox="1322 122 45 45" width="200px">
<!--REM: enxaneta's shape
<rect x="1322" y="122" height="80" width="100" id="sample" stroke="#003300" fill="#6ab150" fill-opacity="0.9" transform="matrix(1,0,0,1,0,0)" />
-->
<!--REM: Sample shape -->
<g id="sample" transform="matrix(0.208522,0.0256033,-0.0546508,0.445095,1023.54,-358.288)">
<g stroke-width="0.1" transform="matrix(1 0 0 1 0 0)">
<path d="m1902.15 1045.16v-46.74h-99.72v46.74z" fill="#1e90ff" fill-rule="evenodd"></path>
<path d="m1902.15 998.42v46.74h-99.72v-46.74z" fill="none" stroke="#fff"></path>
</g>
</g>
</svg>
<!--REM: Inline events for sample case-->
<button onclick="addCurrentDegreesToBody()">show degrees</button>
<button onclick="rotateBy15Degrees()">rotate by 15° (setRotate)</button>
<button onclick="rotateBy15Degrees2()">rotate by 15° (enxaneta)</button>
<button onclick="rotateBy15Degrees3()">rotate by 15° (setRotate with wrap)</button>
<br /><br />
JavaScript
//REM: inserts return of getCurrentRotationOfSVGElementInDegrees(#sample) before the end of </body>
function addCurrentDegreesToBody(){
const
tElement = document.getElementById('sample'),
tDegrees = getCurrentRotationOfSVGElementInDegrees(tElement).toString();
document.body.insertAdjacentHTML('beforeEnd', `${tDegrees}<br />`)
};
//https://stackoverflow.com/questions/27557040/svg-find-rotation-angle-of-a-path
//REM: returns the angle of passed element in degrees
function getCurrentRotationOfSVGElementInDegrees(element){
const
tMatrix = element.transform.baseVal.getItem(0).matrix,
tDegrees = (180 / Math.PI) * Math.atan2(tMatrix.d, tMatrix.c) - 90;
return tDegrees < 0 ? tDegrees + 360 : tDegrees
};
//REM: Rotates #sample by +15° about its center
//REM: and outputs the degrees in the <body>
function rotateBy15Degrees(){
const
tElement = document.getElementById('sample'),
tAngle = getCurrentRotationOfSVGElementInDegrees(tElement),
tMatrix = tElement.transform.baseVal.getItem(0).matrix,
tBBox = tElement.getBBox();
setRotationSVG(
tElement,
tAngle + 15,
tBBox.x + tBBox.width / 2,
tBBox.y + tBBox.height / 2
);
addCurrentDegreesToBody()
};
//REM: Rotates #sample by +15° about its center using enxaneta example
//REM: and outputs the degrees in the <body>
function rotateBy15Degrees2(){
const
tElement = document.getElementById('sample'),
tAngle = getCurrentRotationOfSVGElementInDegrees(tElement),
tMatrix = tElement.transform.baseVal.getItem(0).matrix,
tBBox = tElement.getBBox();
//REM: Creating a new matrix for the rotation
const
tCX = tBBox.x + tBBox.width / 2,
tCY = tBBox.y + tBBox.height / 2,
tRadians = 15 * (Math.PI / 180),
tMatrix2 = tElement.ownerSVGElement.createSVGMatrix();
tMatrix2.a = Math.cos(tRadians);
tMatrix2.b = Math.sin(tRadians);
tMatrix2.c = -Math.sin(tRadians);
tMatrix2.d = Math.cos(tRadians);
tMatrix2.e...