简体   繁体   中英

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. The data for the bar chart is fetched via an ajax request that runs every minute. 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:

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

Here are the docs on it: https://docs.angularjs.org/api/ng/type/ $rootScope.Scope#$watch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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