Skip to content

Instantly share code, notes, and snippets.

@IQAndreas
Created April 9, 2014 06:02
Show Gist options
  • Save IQAndreas/10230280 to your computer and use it in GitHub Desktop.
Save IQAndreas/10230280 to your computer and use it in GitHub Desktop.
// I have to create an entirely new Rectangle class from scratch, because 'Rect' doesn't actually have a
// constructor or any other way of creating your own rectangles.
// http://stackoverflow.com/questions/22953073/does-rect-have-a-constructor-function
function Rectangle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Rectangle.prototype.containsPoint = function(x, y) {
// Clever "use" or "abuse" of `switch`?
switch (true)
{
case (x < this.x):
case (x > this.x + this.width):
case (y < this.y):
case (y > this.y + this.height):
return false;
default:
return true;
}
}
function Slider(x, y, width, height, lineThickness, sliderThickness, startValue) {
this.value = (startValue === undefined) ? 0 : startValue;
this.hitBox = new Rectangle(x, y, width, height);
this.listenTarget = null;
this.listen = function(target) {
this.stopListen();
this.listenTarget = target;
if (target) {
target.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}
}
function onMouseDown(event) {
updateValue(event.clientX);
if (this.hitBox.containsPoint(event.clientX, event.clientY)) {
this.listenTarget.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
this.listenTarget.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
this.listenTarget.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
}
function onMouseMove(event) {
updateValue(event.clientX);
}
function onMouseUp(event) {
updateValue(event.clientX);
this.listenTarget.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
this.listenTarget.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
this.listenTarget.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
function updateValue(clientX) {
this.value = (clientX - x) / width;
if (this.value < 0) { this.value = 0; }
if (this.value > 1) { this.value = 1; }
console.log(this.value);
}
this.stopListen = function() {
if (this.listenTarget) {
this.listenTarget.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
this.listenTarget.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
this.listenTarget.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
}
this.draw = function(context) {
var sx = x + width * this.value;
context.fillStyle = '#999999';
context.fillRect(x, y + (height/2) - (lineThickness/2), width, lineThickness);
context.fillStyle = '#DDDDDD';
context.fillRect(sx - (sliderThickness / 2), y, sliderThickness, height);
}
}
@IQAndreas
Copy link
Author

NOTE: The code doesn't work. Putting it up here for others to look at.

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