Skip to content

Instantly share code, notes, and snippets.

@mamrehn
Created November 11, 2014 14:05
Show Gist options
  • Save mamrehn/e882b5efca09354c387d to your computer and use it in GitHub Desktop.
Save mamrehn/e882b5efca09354c387d to your computer and use it in GitHub Desktop.
Simple example of canvas drawing in Coffeescript, AngularJS using HTML5 Canvas. Interactive: http://plnkr.co/JZrYLo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>AngularJS Canvas Pixel Drawing</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.2/angular.js" data-semver="1.3.2"></script>
<script src="app.js"></script>
</head>
<body ng-app="plunker" ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #000000;"></canvas>
<p>Painted {{someValue | number}} pixels in {{timeUsed}} seconds on canvas!</p>
</body>
</html>
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope) ->
$scope.name = 'Canvas Test'
canvas = document.getElementById("myCanvas")
$scope.canvasWidth = canvas.width
$scope.canvasHeight = canvas.height
$scope.ctx = canvas.getContext("2d")
$scope.canvasData = $scope.ctx.getImageData(0, 0, $scope.canvasWidth, $scope.canvasHeight)
$scope.drawPixel = (x, y, r, g, b, a) ->
index = (x + y * $scope.canvasWidth) * 4
$scope.canvasData.data[index + 0] = r
$scope.canvasData.data[index + 1] = g
$scope.canvasData.data[index + 2] = b
$scope.canvasData.data[index + 3] = a
return
# Actually write to the canvas
$scope.updateCanvas = ->
$scope.ctx.putImageData $scope.canvasData, 0, 0
$scope.canvasData = $scope.ctx.getImageData(0, 0, $scope.canvasWidth, $scope.canvasHeight)
return
getRandomInt = (min, max) ->
Math.floor(Math.random() * (max - min)) + min
#$scope.drawPixel(1, 1, 255, 0, 0, 255)
#$scope.drawPixel(1, 2, 255, 0, 0, 255)
#$scope.drawPixel(1, 3, 255, 0, 0, 255)
start = new Date()
# Just a test, you may use i.e. 5000 for someValue instead
$scope.someValue = Math.floor(Math.random()*10 * $scope.canvasWidth * $scope.canvasHeight)
for i in [0..$scope.someValue]
$scope.drawPixel(
getRandomInt(0, $scope.canvasWidth),
getRandomInt(0, $scope.canvasHeight),
getRandomInt(0, 256),
getRandomInt(0, 256),
getRandomInt(0, 256),
255
)
$scope.updateCanvas()
end = new Date()
$scope.timeUsed = (end.getTime() - start.getTime()) / 1000
#angular.bootstrap(document, ['plunker'])
@mamrehn
Copy link
Author

mamrehn commented Nov 11, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment