Javascript和SVG。有没有办法检测已呈现的文本?

时间:2016-08-21 09:37:21

标签: javascript jquery html angularjs svg

我获得了一些动态生成的svg个元素。它是根据input字段中的文本生成的。

每次中断都意味着新的组元素结构如此

<g>
  <svg>
     <text/>
     <rect/>
  </svg>
</g>

还添加了字体更改选项。因此,在字体更改后,我需要在文本下重新绘制rect,其大小取决于我对text.getBBox()数据的了解。

问题是,当我第一次更改字体时(有事件触发,在select下拉列表中选择其他字体类型后)我的rects不会重新绘制,因为文本没有呈现在<text>元素内部,有没有办法检查,是否所有<text>元素内都呈现了文本?

这是问题的解释

enter image description here

UPD 1

这对我不起作用

someSvgTextBlocks.ready(function() { 
 //call redraw rects functions here
})

UPD 2

可悲的是,拉斐尔的回答也没有帮助我: enter image description here

UPD 3

我使用Angularjs框架,所以这里是角度方式的代码(我猜)

svg stuff的指令视图:

<svg ng-repeat="line in svgConfig.text track by $index">
    <g>
        <rect x="0" y="0" 
            ng-show="svgConfig.rectConfig[$index].active"
            ng-attr-height="{{svgConfig.rectConfig[$index].height}}" 
            ng-attr-width="{{svgConfig.rectConfig[$index].width}}" 
        >
        </rect>

        <text ng-attr-font-family="{{svgConfig.textConfig.fontFamily}}" 
            ng-attr-font-size="{{svgConfig.textConfig.fontSize}}"
            ng-attr-fill="{{svgConfig.textConfig.fontColor}}"
        >
            {{line}}
        </text>     

    </g>

</svg>

指令本身:

app.directive('imageTxtSvgDirective', ['imageTxtSvgService', 'svgUtilsService', function(imageTxtSvgService, svgUtilsService) {

    /**
    * Set event bindings
    */
    var setDomBindings = function($scope, $element, $attrs){
        /**
        * Sets watch to detect changes in text, fontsize, font family to recalculate binded svg-data
        */
        $scope.$watchGroup(['svgConfig.text', 'svgConfig.textConfig.fontSize', 'svgConfig.textConfig.fontFamily', 'svgConfig.extras', 'svgConfig.rectsVisible'], function() {
            var domText = $element.find('text'),
                textExampleList = domText,
                textConfig = $scope.svgConfig.textConfig,
                font = textConfig.fontFamily,
                size = textConfig.fontSize;

            document.fonts.load(''+size + 'px ' + font+'').then(
                function(){
                    $scope.setSvgRectanglesConfig(textExampleList);     
                }
            );
        });
    }

    /*
    * Retruns initialized DOM element
    */
    return {
        restrict: 'E',
        templateUrl: './app/shared/imageTextEditor/imageTxtSvgView.html',
        controller: 'imageTxtSvgController',
        transclude: true,
        link: setDomBindings
    };
}]);

控制器:

app.controller('imageTxtSvgController', ['$scope', 'imageTxtSvgService', '$filter', 'textConfigEnum', function($scope, imageTxtSvgService, $filter, textConfigEnum){

    /**
    * Returns config for each text line rect
    */
    $scope.setSvgRectanglesConfig = function(textAreaList){
        var me = this,
            numberOfElements = (textAreaList) ? textAreaList.length : 0;

        if (numberOfElements <= 0) {
            return;
        }

        $scope.svgConfig.rectConfig = imageTxtSvgService.getSvgRectListData(textAreaList, $scope.svgConfig.rectsVisible, $scope.svgConfig);
    };

    $scope.init = function(){
        // Fonts data
        $scope.textFonts = textConfigEnum.data;

        // Container for svg settings
        $scope.svgConfig = {
            text:'',
            textConfig: {
                fontFamily: $filter('getTextConfigByType')(textConfigEnum.info.Arial).fontFamily,
                fontSize: 20,
                fontDecoration: null,
                fontWeigth: null,
                fontColor:'black'
            },
            rectsVisible: true,
            rectConfig: [],

        };
    };

    $scope.init();
}]);

服务:

    app.service('imageTxtSvgService', ['$rootScope', 'svgUtilsService', function($rootScope, svgUtilsService){

    this.getSvgRectObject = function(data){
        var me = this, 
            rectObject = {
                height: 0,
                width: 0,
                fillColor: '#A8A8A8',
                outlineColor: '#A8A8A8',
                active: false
            };


        return angular.merge({}, rectObject, data);
    }

    /**
    * Handles svg text creation
    */
    this.getSvgText = function(data){
        var me = this,
            text = data.text,
            stringArray = text.split('\n');

        if(text === ""){
            return null;
        }

        return stringArray;
    },

    /**
    * Get data for rect object
    */
    this.getSvgRectData = function(textArea, isActive, prevConfig){
        var me = this,
            box = textArea.getBBox(),
            defaultRectConfig =  {
                height: box.height,
                width: box.width,
                active: isActive
            },
            rectConfig = angular.merge({}, prevConfig, defaultRectConfig);

        return me.getSvgRectObject(rectConfig);
    },

    /**
    * 
    * @returns {Array}
    */
    this.getSvgRectListData = function(textAreaList, isActive, previousConfig){
        var me = this,
            active = isActive,
            previousRectConfig,
            result = [];

        angular.forEach(textAreaList, function(textArea, index) {
            if(previousConfig.rectConfig[index]){
                previousRectConfig = previousConfig.rectConfig[index];
            }

            result.push(me.getSvgRectData(textArea, active, previousRectConfig));
        });

        return result;
    }
}]);

UPD 4:问题解决方案

似乎我已经找到了解决方案。

而不是这个

var domText = $element.find('text'),
                textExampleList = domText,
                textConfig = $scope.svgConfig.textConfig,
                font = textConfig.fontFamily,
                size = textConfig.fontSize;

            document.fonts.load(''+size + 'px ' + font+'').then(
                function(){
                    $scope.setSvgRectanglesConfig(textExampleList);     
                }
            );

它应该是这样的:

var textConfig = $scope.svgConfig.textConfig,
                font = textConfig.fontFamily,
                size = textConfig.fontSize;

            document.fonts.load(''+size + 'px ' + font+'').then(
                function(){
                    var textExampleList = $element.find('text');

                    $scope.setSvgRectanglesConfig(textExampleList);
                    $scope.$apply();        
                }
            );

我应该在字体加载后获得dom数据,但在旧版本中我使用旧版本的dom数据。此外,我忘记了应用更改。

enter image description here

1 个答案:

答案 0 :(得分:4)

我认为您可以使用Font Loading API

var text = 'Text to display';
var font = 'Font to use';
document.fonts.load('12px "'+font+'"', text).then(function() {
  // Here we can be certain the font is available
  // Measure the size now…
});

示例:

var button = document.querySelector('button');
var result = document.querySelector('div');

button.addEventListener('click', function(event) {
  var text = 'The text to rénder';
  // This loads the font (unless already available)
  document.fonts.load('12px "Baloo Paaji"', text).then(function() {
    // Here we can be certain the font is available
    result.style.fontFamily = '"Baloo Paaji"';
    result.textContent = text;
  });
}, false);
<html>

<head>
  <link href="https://fonts.googleapis.com/css?family=Baloo+Paaji" rel="stylesheet">
</head>

<body>
  <button>Load Font</button>
  <div></div>
</body>

</html>

或者,您可以尝试通过在页面中某处(隐藏)的每种字体包含一小段文本来预先加载所有字体。