MCGRAW
MCGRAW

Reputation: 817

Angular canvas directive

im attempting to draw a circle using a canvas element with an angular directive - everything works fine if i draw a rectangle but im having trouble with drawing circles. I can console log the needed parameters for drawing a circle and get the right values but nothing is being rendered. I added the built in $timeout function to see if that would do the trick but it didn't. Any help would be greatly appreciated.

    .directive('circleDraw',['$timeout', function(timer) {
     return {
      restrict: 'A',
      link: function(scope, iElement) {
      var context = iElement[0].getContext('2d');
      var x = iElement.width / 2;
      var y = iElement.height / 2;
      var radius = 90;
      var startAngle = 0 * Math.PI;
      var endAngle;
      var counterClockwise = false;
      var strokeColor;

      function getColor(huh) {
        if (huh <= 49) {
          strokeColor = '#d31f1f';
        } else if (huh <= 74) {
          strokeColor = '#eac11e';
        } else strokeColor = '#59b73c';
        console.log(strokeColor);
        return strokeColor;
      }

      //this test for rectangle works as expected 

      //context.fillStyle = "#FF0000";
      //context.fillRect(20, 20, 150, 150);

      var getDeg = function(inPerc) {
        inPerc = 88;
        var aPerc = (inPerc * 0.02);
        console.log('aPerc = ' + aPerc);
        endAngle = aPerc * Math.PI;
        console.log("end angle = " + endAngle);
        console.log("start angle = " + startAngle);
        context.beginPath();
        context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
        context.lineWidth = 10;
        context.strokeStyle = getColor(inPerc);
        context.stroke();
      }
      timer(getDeg, 0);
    }
  }

the canvas element w/ directive attribute:

<canvas width="200" height="200" circle-draw></canvas>

Upvotes: 2

Views: 1122

Answers (1)

dfsq
dfsq

Reputation: 193301

You are not calculating x and y properly. Fix it like this:

var x = iElement[0].width / 2;
var y = iElement[0].height / 2;

To read width/height properties you need to use raw DOM element which you can access with [0].

Demo: http://plnkr.co/edit/BP4izDLJ3qkkF6XZcjrr?p=preview

By the way, you don't need $timeout to paint on canvas.

Upvotes: 1

Related Questions