2016-05-13 7 views
0

私は、angularJSを使用してhtmlキャンバスにいくつかの円を作成したいと思います。 私はjavascriptを使って同じことをする方法を知っていますが、私はangularJSを初めて利用しており、どんな助けも高く評価されています。AngularJSを使用してhtmlキャンバス要素を作成する

コード:

<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> 
+0

ハイブローリンク:https://github.com/ActivKonnect/angular-circles http://htmlpreview.github.io/?https://github.com/ActivKonnect/angular-circles/ blob/master/example/index.html –

+0

ありがとうございました。あなたの助けをたくさんありがとうございます。しかし、私のコードで作業する方法があるのだろうかと思っていました。 –

答えて

0

実際にあなたのコードの作品。主な問題は、間違った変数(appの代わりにmyapp)で角度アプリにアクセスしようとしたことです。コードを実行しているjsbinがあります。

コントローラでDOMを変更すると、bad practiceとなります。 directiveを使用してDOMオブジェクトにアクセスします。

私はディレクティブ付きの簡単なexampleを作成しました。

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

ディレクティブは、キャンバスの円の位置を設定するために2つのパラメータを取る:これはキャンバスの内部に二つの円を描画する

<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> 

。 これが役立つことを願っています。

+0

ありがとうございます...本当にありがとうございます。:) –

+0

''タグに 'drawCircle'を含めるのを忘れてしまいました。 –

関連する問題