繁体   English   中英

在HTML5画布上绘制条形图,然后将其清除以重新绘制是行不通的

[英]Drawing bar graph on an HTML5 canvas, then clearing it to redraw isn't working

我有一个用于绘制小条形图的AngularJS指令。 条形图的数据是通过每分钟运行的ajax请求获取的。 第一次,条形图绘制得很好。 下次,我想清除画布,然后使用新获取的值重新绘制条形图。 但是,当我清除画布时,条形图不会重绘。

angular.module('statsApp')
  .directive('miniChart', function () {
    return {
      template: '<canvas width="100" height="50"></canvas>',
      restrict: 'E',
      replace: 'true',
      scope: {
        values: '=',
        property: '@',
        color: '@',
        colorZero: '@'
      },
      link: function(scope, element) {
        var posX = 0;
        var canvas = element[0];
        scope.$watch('values', function(values) {
          if(values) {
            var barMargin = 3;
            var barWidth = Math.abs(canvas.width / 7) - barMargin;
            var ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            angular.forEach(values, function(value) {
              console.debug(value);
              ctx.fillStyle = value[scope.property] > 0 ? scope.color : scope.colorZero;
              var rectHeight = value[scope.property] + 1;
              ctx.fillRect(posX, Math.abs(rectHeight - canvas.height), barWidth, rectHeight);
              posX += (barWidth + barMargin);
            });
          }
        });
      }
    };
  });

不知道如何从服务器填充值,但是您的手表可能需要随后传递的,true参数来进行完整检查,如下所示:

scope.$watch('values', function(values) {
    ...
}, true);

这是上面的文档: https : //docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ watch

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM