1

I am building a custom AngularJS 1 directive, based on a canvas. But I can't see the rectangle I am drawing on the canvas :

angular.module('loloof64.chess_diagram', [])
  .directive('chessDiagram', function() {
    return {
      restrict: "E",
      template: '<canvas width="{{size}}" height="{{size}}"></canvas>',
      scope: {
        size: '@'
      },
      compile: function(element, attrs) {

        drawBackground = function(scope, canvasCtx) {
          canvasCtx.fillStyle = "#DD55CC";
          canvasCtx.fillRect(0, 0, scope.size, scope.size);
        };


        return function(scope, element, attrs) {
          scope.size = scope.size - scope.size % 9;
          scope.cellSize = Math.floor(scope.size / 9);
          canvas = element[0].children[0];
          ctx = canvas.getContext("2d");
          drawBackground(scope, ctx);
        };

      }
    };
  });

Here is my plunker live preview

loloof64
  • 5,252
  • 12
  • 41
  • 78

1 Answers1

1

Issue here is that you are calling fillRect before dom has finished rendering. There is already a thread on StackOverFlow for that.

Wrap you call to drawBackground within $timeout with zero delay.

$timeout(function() {
    drawBackground(scope, ctx);
});

And also don't forget to inject $timeout in your directive:

.directive('chessDiagram', function($timeout) {

Further scope.size is NaN. Give it a value may be in html like this

<chess-diagram size="100"></chess-diagram>
Community
  • 1
  • 1
Adnan Umer
  • 3,669
  • 2
  • 18
  • 38