0

I want to create some circles in an html canvas using angularJS. I know how to do the same using javascript but i am new to angularJS and any help is highly appreciated.

Code:

<title>Home Page</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>



</head>

<body>

<div  ng-app="myapp" ng-controller="myctrl">
<canvas id="canvas" width="2100" height="900" 
    style="border: 1px solid #d3d3d3;">
</canvas>
</div>
<script>

var $scope;
var app = angular.module('myapp', []);
myapp.controller("myctrl", function($scope){
var c1 = document.getElementById("canvas");
var ctx = c1.getContext("2d");
ctx.beginPath();
ctx.arc(500, 500, 50, 0, 2 * Math.PI, false);
ctx.lineWidth = 0.2;
ctx.stroke();
ctx.fill();
})

</script>
</body>
Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
swati jain
  • 1
  • 1
  • 1
  • hi please check blow link : https://github.com/ActivKonnect/angular-circles also http://htmlpreview.github.io/?https://github.com/ActivKonnect/angular-circles/blob/master/example/index.html – Nikhil Vaghela May 13 '16 at 06:03
  • Thanks a lot for your help.. but i was wondering if there is a way to work with my code. – swati jain May 13 '16 at 06:33

1 Answers1

0

Actually your code works. The main problem is that you tried to access your angular app by the wrong variable(myapp instead of app). Here is a jsbin that is running your code.

But altering the DOM in a controller is bad practice. Use a directive to access the DOM objects.

I created a simple example with a directive.

app.directive('drawCircle', function() {
return {
  scope: {
    x: '@x',
    y: '@y'
  },
  link: function(scope, element, attrs) {
    var x = parseInt(scope.x);
    var y = parseInt(scope.y);
    var canvas = element.parent();
    var ctx = canvas[0].getContext("2d");
    ctx.beginPath();
    ctx.arc(x, y, 50, 0, 2 * Math.PI, false);
    ctx.lineWidth = 0.2;
    ctx.stroke();
    ctx.fill();
  }
}
});

The directive takes two parameters to set the position of the circle in a canvas:

<canvas id="canvas" width="2100" height="900" style="border: 1px solid #d3d3d3;">
  <draw-circle x="500" y="500"></draw-circle>
  <draw-circle x="200" y="500"></draw-circle>
</canvas>

This will draw two circles inside the canvas. Hope this helps.

Community
  • 1
  • 1
k4l4m
  • 423
  • 2
  • 4
  • 11