<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="//code.angularjs.org/1.1.3/angular.js"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <div id="d">
      <h1>Simple Canvas Drawing Directive in AngularJS</h1>
      <h4>click and drag to draw!</h4>
      <canvas width="500" height="300" id="canvas" drawing></canvas>
    
      <p style="color:#9ac">by <a href="http://justgoscha.github.io">justGoscha</a></p>

    </div>
  </body>

</html>
var app = angular.module("app", []);

app.directive("drawing", function(){
  return {
    restrict: "A",
    link: function(scope, element){
      var ctx = element[0].getContext('2d');
      
      // variable that decides if something should be drawn on mousemove
      var drawing = false;
      
      // the last coordinates before the current move
      var lastX;
      var lastY;
      
      element.bind('mousedown', function(event){
        
        lastX = event.offsetX;
        lastY = event.offsetY;
        
        // begins new line
        ctx.beginPath();
        
        drawing = true;
      });
      element.bind('mousemove', function(event){
        if(drawing){
          // get current mouse position
          currentX = event.offsetX;
          currentY = event.offsetY;
          
          draw(lastX, lastY, currentX, currentY);
          
          // set current coordinates to last one
          lastX = currentX;
          lastY = currentY;
        }
        
      });
      element.bind('mouseup', function(event){
        // stop drawing
        drawing = false;
      });
        
      // canvas reset
      function reset(){
       element[0].width = element[0].width; 
      }
      
      function draw(lX, lY, cX, cY){
        // line from
        ctx.moveTo(lX,lY);
        // to
        ctx.lineTo(cX,cY);
        // color
        ctx.strokeStyle = "#4bf";
        // draw it
        ctx.stroke();
      }
    }
  };
});
/* Styles go here */

body{
    font-family: "Eau Naturelle", "Helvetica", "Arial", "Lucida Grande", "Gill Sans", "Verdana", sans-serif;
  font-weight:100;
  color: #444;
 background-color: #ddd; 
}

#canvas{
  border-bottom: 1px solid rgba(0,0,0,0.3); 
  background-color: #FFF;
  box-shadow: 0 9px 20px -5px rgba(0,0,0,0.8);
}

#d{
  text-align: center;
}

h1{
  color: #444;
  font-family: "Eau Naturelle", "Helvetica", "Arial", "Lucida Grande", "Gill Sans", "Verdana", sans-serif;
  font-weight: 500;
}

a{
  color: #4a9;
  text-decoration:none;
  font-style:italic;
  font-weight: 800;
}