简体   繁体   English

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

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

I have an AngularJS directive that is used to draw a small bar chart. 我有一个用于绘制小条形图的AngularJS指令。 The data for the bar chart is fetched via an ajax request that runs every minute. 条形图的数据是通过每分钟运行的ajax请求获取的。 The first time through, the bar chart is drawn just fine. 第一次,条形图绘制得很好。 The next time through, I want to clear the canvas, and redraw the bar chart with the newly fetched values. 下次,我想清除画布,然后使用新获取的值重新绘制条形图。 However when I clear the canvas, then the bar chart isn't redrawn. 但是,当我清除画布时,条形图不会重绘。

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);
            });
          }
        });
      }
    };
  });

Not to sure how you populate values from the server, but your watch might need the ,true parameter passed afterwards to do the full check like this: 不知道如何从服务器填充值,但是您的手表可能需要随后传递的,true参数来进行完整检查,如下所示:

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

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

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

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