fabric.js - kitchensink - 选择对象时刷新对象控件

时间:2018-01-31 15:30:25

标签: javascript fabricjs

拉起厨房。选择左侧的i-text对象" lorem ipsum"并点击对象选项卡: http://fabricjs.com/kitchensink

您会注意到"文字特定控件"反映i-text对象的内容。现在点击画布背景(从而取消选择对象),最后点击右侧" foo bar" i-text对象。文本控件再次反映了i-text对象的内容。

到目前为止一切顺利。

我不明白为什么在没有先单击画布背景的情况下单击其他i-text对象时控件不会更新。除非您单击一个i-text对象,否则控件似乎仍然锁定在第一个对象上。实际上,您可以在textarea中输入一些文本,然后选择另一个替换整个内容的i-text对象。

当在i-text对象之间切换时,如何清除文本控件中的先前选择?

谢谢!

1 个答案:

答案 0 :(得分:1)

Kitchensink是用古老的Angular.js 1.2编写的。

因此,如果您点击Chrome开发者工具中的text specific controls DOM元素,您会看到其html代码为:<div id="text-wrapper" ng-show="getText()">

让我们在http://fabricjs.com/js/kitchensink/controller.js中找到这个getText()函数。事实证明,它使angular.js摘要循环监听fabric.js API调用(第108-113行):

$scope.getText = function() {
  return getActiveProp('text');
};
$scope.setText = function(value) {
  setActiveProp('text', value);
};

因此,要在文本特定控件中刷新文本,显然,您需要在切换到其他文本时调用Fabric setActiveProp('text', value)

text-specific-controls中的文字区域内容使用http://fabricjs.com/js/kitchensink/app_config.js中的bind-value-to="text"指令:

kitchensink.directive('bindValueTo', function() {
  return {
    restrict: 'A',

    link: function ($scope, $element, $attrs) {

      var prop = capitalize($attrs.bindValueTo),
          getter = 'get' + prop,
          setter = 'set' + prop;

      $element.on('change keyup select', function() {
        if ($element[0].type !== 'checkbox') {
          $scope[setter] && $scope[setter](this.value);
        }
      });

      $element.on('click', function() {
        if ($element[0].type === 'checkbox') {
          if ($element[0].checked) {
            $scope[setter] && $scope[setter](true);
          }
          else {
            $scope[setter] && $scope[setter](false);
          }
        }
      })

      $scope.$watch($scope[getter], function(newVal) {
        if ($element[0].type === 'radio') {
          var radioGroup = document.getElementsByName($element[0].name);
          for (var i = 0, len = radioGroup.length; i < len; i++) {
            radioGroup[i].checked = radioGroup[i].value === newVal;
          }
        }
        else if ($element[0].type === 'checkbox') {
          $element[0].checked = newVal;
        }
        else {
          $element.val(newVal);
        }
      });
    }
  };
});

该指令只是监视绑定属性的getter和setter(在我们的案例中,binded属性是text,因此它会监视getText() / setText()并反映UI中的任何更改。