How to replace obsolete "svgElement.offsetWidth / height" in Chrome

Chrome Platfrom announces that it will reject offsetWidth soon. And he suggests developers use getBoundingClientRect ().

But when there is scale , they are different.

<div id="wrap"  style="transform: scale(2); width:300;height:300;">
   <svg id="real" style="border:red 10px solid;" >
     <rect/>
   </svg>
</div>

<script>
var e = document.getElementById("real");
var rect = e.getBoundingClientRect(); 
console.log(e.offsetWidth);  //320
console.log(e.clientWidth);  //300
console.log(rect.width);     //640   
</script>      

In my other question , I tried to find the official API to get the scale, but failed.

How to replace the obsolete "svgElement.offsetWidth / height / parent" with Chrome when there is scale?

One way I can think of is to get the width of the border and add it to clientWidth. Are there any api to get svg border? Using e.style.borderRightWidth and parsing strings doesn't look nice.

Any response or comment will be appreciated.

+4
1

- transform , rect, :

function getOffsetWidth(elm) {
  var cur, i;
  var saveTransforms = [];

  i = 0;
  cur = elm;
  //set the transform to '' for all ancestors
  while (cur) {
    if (cur.style) {
      saveTransforms[i] = cur.style.transform;
      cur.style.transform = '';
    }
    i++;
    cur = cur.parentNode;
  }
  var rect = e.getBoundingClientRect();

  i = 0;
  cur = elm;


  //restore the transform for all ancestors
  while (cur) {
    if (cur.style) {
      cur.style.transform = saveTransforms[i];
    }
    i++;
    cur = cur.parentNode;
  }


  return rect.width;
}

jsfiddle

0

Source: https://habr.com/ru/post/1629989/


All Articles