Monday, August 21, 2017

Fun with Angular and an HTML 5 canvas.

I updated my canvas-drawing post from 2014. Now it uses AngularJS instead of JQuery. Angular rocks.

Fiddle, GitHub

It doesn't embed well in blogger though.
The HTML:
<div ng-controller="CanvasController" style="font-family: 'arial'">
<canvas
id="myCanvas"
style="border: solid;"
ng-init="myCanvas=this"
ng-mousedown="onMouseDown($event)"
ng-mousemove="onMouseMove($event)"
ng-mouseup="onMouseUp($event)"
ng-mouseleave="onMouseLeave($event)">
</canvas>
<button id="clearButton" ng-click="onClearButtonClick($event)">Clear</button>
<br />
<h1>{{ x }} {{y}}</h1>
<h3>Is Drawing: {{isDrawing}} </h3>
</div>
The javascript:
<code>
var myApp = angular.module('myApp', []);
myApp.controller("CanvasController", function($scope) {
//console.log("OtherController");
$scope.isDrawing = false;
$scope.x = 0;
$scope.y = 0;
$scope.lastLine = null;
$scope.onClearButtonClick = function($event) {
//console.log("onClearButtonClick");
var ctx = myCanvas.getContext("2d");
ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
}
$scope.onMouseDown = function($event) {
//console.log("OnMouseDown");
$scope.isDrawing = true;
}
$scope.onMouseUp = function($event) {
//console.log("OnMouseUp");
$scope.isDrawing = false;
$scope.lastLine = null;
}
$scope.onMouseMove = function($event) {
//console.log("onMouseMove");
var ctx = myCanvas.getContext("2d");
var clientRect = myCanvas.getBoundingClientRect();
var x = ($event.pageX - clientRect.left);
$scope.x = x;
var y = ($event.pageY - clientRect.top);
$scope.y = y;
if (!$scope.isDrawing) {
return;
}
if ($scope.lastLine != null) {
ctx.beginPath();
ctx.moveTo($scope.lastLine[0], $scope.lastLine[1]);
ctx.lineWidth = 5;
ctx.lineTo(x, y);
ctx.stroke();
}
$scope.lastLine = [x, y];
}
$scope.onMouseLeave = function($event) {
//console.log("onMouseLeave");
$scope.isDrawing = false;
$scope.lastLine = null;
}
});
</code>
view raw gistfile1.txt hosted with ❤ by GitHub