Skip to content

Instantly share code, notes, and snippets.

@richardwestenra
Created August 29, 2013 09:47
Show Gist options
  • Save richardwestenra/6376177 to your computer and use it in GitHub Desktop.
Save richardwestenra/6376177 to your computer and use it in GitHub Desktop.
Click the button JavaScript. See http://richardwestenra.com/click-the-button/
$(function(){
// Define some global variables:
var timeStamp = {
start: 0,
stop: 0,
duration: 0
};
// Calculate how close a number is to 5.
function getProximity(num){
return Math.abs(5 - num)
}
var highScores,
closestAttempts,
lowestHighScore,
username
lowScoreBoundary = 2,
highScoreBoundary = 8;
// dataCount;
// var extremeScore = function(){
// return timeStamp.duration >= highScoreBoundary || (timeStamp.duration <= lowScoreBoundary && timeStamp.duration !== 0);
// }
// Set Apigee account details
if(typeof Usergrid === 'undefined'){
var apigeeIsSupported = false;
console.log("Usergrid is undefined");
} else {
var apigeeIsSupported = true;
var client = new Usergrid.Client({
orgName:'richardwestenra',
appName:'sandbox'
});
}
// Send the latest result to Apigee and return the most recent result.
var sendApigeeData = function(){
if(!apigeeIsSupported) {
getAjaxData();
return;
}
// Set some details for your first object
var options = {
type: 'timer',
// name: 'time'+dataCount,
startTime: timeStamp.start,
stopTime: timeStamp.stop,
duration: timeStamp.duration,
username: (typeof username == "undefined") ? "Anonymous" : _.escape(username)
};
// Now, run it!
client.createEntity(options, function (error, response) {
if (error) { // Error
// $('#apigeeResult').html("Oops, we had a connection failure.");
console.log("Oops, we had a connection failure.");
} else { // Success
// var runTime = (response.get("stopTime") - response.get("startTime"))/1000;
// $('#apigeeResult').html("You actually took " +response.get("duration")+" seconds.");
console.log("Data sent successfully.");
getAjaxData();
}
});
/*
client.createCollection(options, function(error, times){
$("#prevTimes").html("");
while(times.hasNextEntity()) {
//Put your call to .getNextEntity() below.
var time = times.getNextEntity();
// var runTime = (time.get("stopTime") - time.get("startTime"))/1000;
$("#prevTimes").append("<li>"+time.get("duration")+" seconds</li>");
}
});
*/
};
// Calculate the highest scores:
function calculateHighScores(data){
highScores = _.chain(data.entities)
.sortBy(function(val){ return getProximity(val.duration); })
.first(10)
._wrapped;
if(highScores.length>0) {
lowestHighScore = getProximity(_.last(highScores).duration);
} else {
lowestHighScore = Infinity;
}
return highScores;
}
// Create the histogram chart from Apigee data via JSONP
function getAjaxData(){
$('#spinner').show();
var ajaxTimesArray = [];
// var urlQuery = '';
// extremeScore();
// console.log(extremeScore());
// var urlQuery = extremeScore() ? '' : '&ql=select * where duration<'+highScoreBoundary+' and duration>'+lowScoreBoundary;
var urlQuery = '&ql=select * where duration<'+highScoreBoundary+' and duration>'+lowScoreBoundary;
$.ajax({
url: 'https://api.usergrid.com/richardwestenra/sandbox/timers?limit=9999'+urlQuery,
dataType: 'jsonp',
cache: false,
crossDomain: true,
contentType: "application/json",
success: function(data){
$('#spinner').fadeOut(200);
// var prevTimes = '';
$.each(data.entities, function(key,val){
ajaxTimesArray.push(val.duration);
// prevTimes += val.duration+', ';
});
console.log(ajaxTimesArray);
// $("#prevTimes").html(ajaxTimesArray.length+ ' times recorded so far.').attr('title',prevTimes.substring(0,prevTimes.length-2));
// dataCount = ajaxTimesArray.length;
histogramChart(ajaxTimesArray,timeStamp.duration);
highScoresHTML = '<tr><th colspan="2">Name</th><th>Time</th></tr>'
$.each(calculateHighScores(data),function(key,val){
highScoresHTML += '<tr><td style="width:20px;">'+(key+1)+'.</td><td>'+val.username+'</td><td>'+val.duration.toFixed(3)+'</td></tr>';
});
$('#highScores').html(highScoresHTML);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(+jqXHR+" "+textStatus+" "+errorThrown);
}
});
}
getAjaxData();
function getRotationDegrees(obj) {
var matrix = obj.css("-webkit-transform") ||
obj.css("-moz-transform") ||
obj.css("-ms-transform") ||
obj.css("-o-transform") ||
obj.css("transform");
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { var angle = 0; }
return (angle < 0) ? angle +=360 : angle;
}
// Make things happen when you click the button:
$('#clicker').click(function(){
if(!$(this).hasClass('timerRunning')) {
// Timer isn't running so run it
timeStamp.start = new Date().getTime();
$(this).text("Stop timer").addClass('timerRunning btn-danger');
$('#apigeeResult').slideUp(400,function(){ $(this).html("")});
$("#prevTimesContainer").slideUp();
$('.clockHand').addClass('paused');
} else {
// Stop the timer and do stuff
timeStamp.stop = new Date().getTime();
timeStamp.duration = parseFloat((timeStamp.stop - timeStamp.start)/1000);
$(this).text("Start timer").removeClass('timerRunning btn-danger');
$('#apigeeResult').html("You actually took " + timeStamp.duration.toFixed(3)+" seconds.").slideDown();
if(getProximity(timeStamp.duration) < lowestHighScore || highScores.length<10) {
if(typeof username == "undefined") {
username = prompt("You got a new high score! Please enter your name:");
} else {
alert("Congratulations "+username+", you got another high score!");
}
}
sendApigeeData();
$('.clockHand').removeClass('paused');
}
});
// Set up histogram
function histogramChart(values, latestTime) {
/*for(i=0;i<10000;i++){
values.push(parseFloat((Math.random()*10).toFixed(2)));
}*/
if(typeof d3 === 'undefined'){
console.log("d3 is undefined");
return;
}
// Generate an Irwin–Hall distribution of 10 random variables.
// var values = d3.range(1000).map(d3.random.irwinHall(10));
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {top: 20, right: 10, bottom: 20, left: 10},
width = 520 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom,
// xMin = Math.floor(d3.min(values, function(d) { return d; })),
xMin = 0,
// Only show times greater than 10 if the user's time was >10
// xMax = (latestTime>10) ? Math.ceil(d3.max(values, function(d) { return d; })) : 10,
// xMin = extremeScore() ? 0 : lowScoreBoundary,
// xMax = extremeScore() ? Math.ceil(d3.max(values, function(d) { return d; })) : highScoreBoundary,
// TICKS = extremeScore() ? (xMax-xMin)*5 : (xMax-xMin)*10,
xMin = lowScoreBoundary,
xMax = highScoreBoundary,
TICKS = (xMax-xMin)*10,
barIncrement = xMax/TICKS;
console.log(xMin, xMax);
var x = d3.scale.linear()
.domain([xMin, xMax])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(TICKS))
(values);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
$("#histogram").remove();
var svg = d3.select("#graphContainer").append('svg')
.attr('id','histogram')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", function(d) {
if(latestTime>0 && latestTime < d.x+barIncrement && latestTime >= d.x) {
return "bar selected";
} else {
return "bar";
}
})
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", width/TICKS -1)
// .attr("width", function(d){
// console.log(x(d.dx) - 1);
// return x(d.dx) - 1;
// })
.attr("height", function(d) {
// console.log(data);
return height - y(d.y);
});
bar.append("text")
.attr("dy", ".75em")
.attr("y", -16)
// .attr("x", x(data[0].dx) / 2)
.attr("x", width/TICKS / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.y); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
/*if(latestTime>0){
svg.append("svg:line").attr("class", "latestTime")
.attr("x1",0).attr("y1",0)
.attr("x2",0).attr("y2",height)
.attr("transform", "translate(" + (x(latestTime)) + ",0)");
}*/
svg.append("svg:line").attr("class", "targetLine")
.attr("x1",0).attr("y1",0)
.attr("x2",0).attr("y2",height)
.attr("transform", "translate(" + (x(5)) + ",0)");
}
function canvasSpinner(target,size){
var ctx,
drawIntervalID,
canvas = document.getElementById(target),
spokes = 16, // Number of spokes on the wheel
w = canvas.width = size, h = canvas.height = size,
innerRadius = w/5,
outerRadius = w/2.5,
lineWidth = w/15,
drawInterval = 75;
if (canvas.getContext){
ctx = canvas.getContext('2d');
ctx.translate(w/2,h/2); // Center the origin
ctx.lineWidth = lineWidth;
ctx.lineCap = "round"
drawIntervalID = setInterval(draw,drawInterval);
return drawIntervalID;
function draw(){
ctx.clearRect(-w/2,-h/2,w,h); // Clear the image
ctx.rotate(Math.PI*2/spokes); // Rotate the origin
for (var i=0; i<spokes; i++) {
ctx.rotate(Math.PI*2/spokes); // Rotate the origin
ctx.strokeStyle = "rgba(0,0,0,"+ i/spokes +")"; // Set transparency
ctx.beginPath();
ctx.moveTo(0,innerRadius);
ctx.lineTo(0,outerRadius);
ctx.stroke();
}
}
}
}
canvasSpinner('spinner',80);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment