Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBoundingClientRect() returning wrong width

I'm using Angular Material for my grid system. I'm trying to generate an SVG and it is supposed to show me the width of the element, however it is getBoundingClientRect() is returning 300px despite the width being 618px. I tried it again making my window smaller but it still showed up as 300px even though this time it was actually 100px..

This is my HTML:

<div layout="row" layout-wrap layout-padding>
    <div flex="33" ng-repeat="result in ctrl.results">
        <svg height="100%" width="100%" position>
          <rect x="0" y="0" width="100%" height="100%" fill="#da552f"></rect>
          <text fill="#ffffff" x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-size="48" font-family="Verdana">Hello World</text>
        </svg>
    </div>
</div>

and this is my angularjs directive for the position attribute:

var app = angular.module('MainDirective', []);

app.directive('position', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attrs) {
            var rect = element[0].getBoundingClientRect();
            var text = element.children()[1].getBBox();
            console.log(rect)
        }
    };
});

There is no custom CSS in my project.

Any thoughts why this might be happening? I've tried so many different variations of getBoundingClientRect() but they all returned 300...

Edit: just as proof:

enter image description here

like image 812
Katie Avatar asked Oct 18 '22 20:10

Katie


1 Answers

I figured out what my issue was.. I should've used angulars $scope.$watch as I was generating the svg on an event click.

var app = angular.module('MainDirective', []);

app.directive('position', function () {
    return {
        restrict: 'A',
        link: function ($scope, element, attrs) {
            var rect, image, text;
            $scope.$watch(element, function () {
                rect = element[0].clientWidth;
                image = element.children()[1].getBBox();
                text = element.children()[2].getBBox();
                console.log("Rect: "+rect+" image: "+image.width+" text: "+text.width)
            });
        }
    };
});
like image 60
Katie Avatar answered Oct 20 '22 11:10

Katie