Skip to content

Instantly share code, notes, and snippets.

@zbabtkis
Created May 10, 2013 17:03
Show Gist options
  • Save zbabtkis/5555784 to your computer and use it in GitHub Desktop.
Save zbabtkis/5555784 to your computer and use it in GitHub Desktop.
var AngleControlView = Backbone.View.extend({
tagName: 'canvas',
className: 'angle-control',
initialize: function() {
_.bindAll(this);
this.el.height = 200;
this.el.width = 200;
// Defaults for drawing background circle.
this.centerX = this.el.width / 2;
this.centerY = this.el.height / 2;
this.canvasR = this.centerX - 10;
this.drawCircle();
// Events for collecting coordinates and redrawing.
this.$el.on('mouseenter mousemove', this.movePointer);
this.$el.on('click', this.getValues);
this.$el.on('mousedown', this.active);
},
ctx: function() {
return this.el.getContext('2d');
},
drawCircle: function() {
// Border
this.ctx().beginPath();
this.ctx().arc(this.centerX, this.centerY, this.canvasR, 0, 2 * Math.PI*2, false);
this.ctx().fillStyle = "#111";
this.ctx().fill();
this.ctx().lineWidth = 5
this.ctx().strokeStyle = "#eee";
this.ctx().stroke();
// Crosshair
this.ctx().lineWidth = 1;
this.ctx().moveTo(this.centerX, 10);
this.ctx().lineTo(this.centerX, this.el.width - 10);
this.ctx().moveTo(10, this.centerY);
this.ctx().lineTo(this.el.height - 10, this.centerY);
this.ctx().stroke();
},
drawPointer: function(x, y, color, dist) {
var rad = (dist + 10 || 100)/10;
// Draws small circle to select camera angle.
this.ctx().beginPath();
this.ctx().arc(x, y, rad, 0, 2 * Math.PI, false);
this.ctx().fillStyle = color;
this.ctx().fill();
},
removePointer: function() {
this.ctx().clearRect(0, 0, this.el.width, this.el.height);
},
inBoundary: function(x, y) {
var dist, distX, distY;
// Formula for calculating distance between center and pointer.
distX = Math.abs(this.centerX - x);
distY = Math.abs(this.centerY - y);
dist = Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
return(dist);
},
movePointer: function(e, color) {
var x, y, dist;
x = e.pageX - this.$el.offset().left;
y = e.pageY - this.$el.offset().top;
color = color || '#09f';
dist = this.inBoundary(x, y);
// Make sure pointer is inside background-circle.
if(dist <= this.canvasR) {
this.el.style.cursor = 'none';
this.removePointer();
this.drawCircle();
this.drawPointer(x, y, color, dist);
} else {
this.el.style.cursor = 'normal';
}
},
active: function(e) {
// Draw pointer as orange if when user clicks a point.
this.movePointer(e, 'orange');
},
getValues: function(e) {
var x, y, scale, args;
// Get current point on the graph for sending to Robot model.
x = e.pageX - this.el.offsetLeft + ',13';
y = '13,' + e.pageY - this.el.offsetTop ;
// For camera to set camera position.
args = {
'width': x,
'height': y,
'imgWidth': this.el.width,
'imgHeight': this.el.height
};
// Send command to Robot.
app.Model.Robot.robotCommand('position', args);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment