1

I'm trying to draw a circle wherever the user clicks on the screen using angular on canvas. My code doesn't seem to be working. Here's my plnk

http://plnkr.co/edit/rYVLgB14IutNh1F4MN6T?p=preview

var app = angular.module('plunker', []);

app.controller('MainController', function($scope) {
  //alert("test");
  $scope.doClick = function(event){

     var x = event.clientX;
     var y = event.clientY;
     var offsetX = event.offsetX;
     var offsetY = event.offsetY;

      //alert(x, y, offsetX, offsetY);

      //console.log(x, y, offsetX, offsetY);

      var ctx = getContext("2d");

    //draw a circle
      ctx.beginPath();
      ctx.arc(x, y, 10, 0, Math.PI*2, true); 
      ctx.closePath();
      ctx.fill();
  };

  $scope.test="test";
});

Any help appreciated.

Thomas
  • 25
  • 1
  • 4
  • try putting it in a service, services make better use of vanilla javascript. – floor Apr 11 '15 at 15:59
  • I'm trying not to use vanilla javascript. Could you suggest a way to do in in purely angular – Thomas Apr 11 '15 at 16:02
  • I don't know if angular out the box has any neat canvas utilities, you may need to the browser the list of angular modules for what you want. – floor Apr 11 '15 at 16:03
  • And by the looks of your code you are not using canvas right. you need to use document.getElementById or something and bind that to ctx in the getContext. – floor Apr 11 '15 at 16:05
  • So I got your code to work, I will post the answer. – floor Apr 11 '15 at 16:08

1 Answers1

2

So the problem here is not using canvas correctly.

You need to add an ID, Class or target all canvas elements, In this case I added an ID to your canvas element this way I can target it with document.getElementById

<canvas id="canvas" ng-click="doClick($event)" width="600" height= "600"></canvas>

And in your javascript you weren't targeting the canvas element and applying the context to it.

So this is what your new doubleCLick function will look like:

$scope.doClick = function(event){

 var x = event.clientX;
 var y = event.clientY;
 var offsetX = event.offsetX;
 var offsetY = event.offsetY;
 alert(x, y, offsetX, offsetY);

 /// These are the 2 new lines, see you target the canvas element then apply it to getContext
 var canvasElement = document.getElementById("canvas");
 var ctx = canvasElement.getContext("2d");

  //draw a circle
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, Math.PI*2, true); 
  ctx.closePath();
  ctx.fill();

};

I still recommend putting this code in a service.

floor
  • 1,519
  • 11
  • 24
  • This code seems to be working but it's not drawing the circle exactly where I click. Drawing it a bit below. Also I really don't know much about services in angular. Really a noob with front-end technology. – Thomas Apr 11 '15 at 16:26
  • And check out this page for an answer about the mouse position: http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas – floor Apr 11 '15 at 16:38