Skip to content

Instantly share code, notes, and snippets.

@jamespantalones
Created October 21, 2015 10:01
Show Gist options
  • Save jamespantalones/8dc11e4b619c3889e748 to your computer and use it in GitHub Desktop.
Save jamespantalones/8dc11e4b619c3889e748 to your computer and use it in GitHub Desktop.
Canvas Overlays
'use strict';
/**
* @ngdoc service
* @name progApp.overlayService
* @description
* # overlayService
* Factory in the progApp.
*/
angular.module('progApp').factory('Overlays', function () {
// ------------------------------------------------
// Overlay constructor
//
function Overlay(state, image, x, y, w, h){
this.state = state;
this.image = image;
this.x = x || 0;
this.y = y || 0;
this.w = w || 1;
this.h = w || 1;
}
Overlay.prototype = {
// ------------------------------------------------
// See if in bounds
//
contains: function(mx, my){
return (this.x <= mx) && (this.x + this.w >= mx) &&
(this.y <= my) && (this.y + this.h >= my);
},
draw: function(ctx, optionalColor){
var i;
var cur;
var half;
ctx.fillStyle = this.fill;
ctx.drawImage(this.image.image, this.x, this.y, this.w, this.h);
if (this.state.selection === this) {
ctx.strokeStyle = this.state.selectionColor;
ctx.lineWidth = this.state.selectionWidth;
ctx.strokeRect(this.x,this.y,this.w,this.h);
// draw the boxes
half = this.state.selectionBoxSize / 2;
// 0 1 2
// 3 4
// 5 6 7
this.state.selectionHandles[0].x = this.x-half;
this.state.selectionHandles[0].y = this.y-half;
this.state.selectionHandles[1].x = this.x+this.w/2-half;
this.state.selectionHandles[1].y = this.y-half;
this.state.selectionHandles[2].x = this.x+this.w-half;
this.state.selectionHandles[2].y = this.y-half;
//middle left
this.state.selectionHandles[3].x = this.x-half;
this.state.selectionHandles[3].y = this.y+this.h/2-half;
//middle right
this.state.selectionHandles[4].x = this.x+this.w-half;
this.state.selectionHandles[4].y = this.y+this.h/2-half;
//bottom left, middle, right
this.state.selectionHandles[6].x = this.x+this.w/2-half;
this.state.selectionHandles[6].y = this.y+this.h-half;
this.state.selectionHandles[5].x = this.x-half;
this.state.selectionHandles[5].y = this.y+this.h-half;
this.state.selectionHandles[7].x = this.x+this.w-half;
this.state.selectionHandles[7].y = this.y+this.h-half;
ctx.fillStyle = this.state.selectionBoxColor;
for (i = 0; i < 8; i += 1) {
cur = this.state.selectionHandles[i];
ctx.fillRect(cur.x, cur.y, this.state.selectionBoxSize, this.state.selectionBoxSize);
}
}
}
};
// Public API here
return {
newOverlay: function (state, image, x, y, w, h) {
return new Overlay(state, image, x, y, w, h);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment