I have a canvas item that has several variables determining the speed of the "particles" I am generating. I have it setup so that when you log in the canvas updates and changes color(basically I am using a php session variable to reitterate the js code for the canvas to change a few variables on it) I am using ajax to reload the page with the canvas within the main page(so the whole page does not reload). When ever it reloads the canvas page via ajax the speed of the particles increases. When I reload with the reload button it does not increase. Is there a way to reset the canvas in between the ajax(I have tried using canvas.delete("all"); and canvas.delete("speed"); but it continues to speed up the canvas particles with each ajax reload. Any ideas?
Here is the canvas fork I created and am working with.
<div id="isohold">
<canvas id="iso"></canvas>
<div id="loghold">Login</div>
</div>
<?php
session_start();
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['userid'])){
$userid = $_SESSION['userid'];
echo " <script>
'use strict';
var rn = function rn(min, max) {
return Math.random() * (max - min) + min;
};
var ctx = iso.getContext('2d');
var _window = window;
var w = _window.innerWidth;
var h = _window.innerHeight;
var t = 10;
var arr = [];
var cn = 200;
var rad = 300;
var sp = rn(1, 5) / 10000;
iso.width = w;
iso.height = h;
while (~ ~ cn--) {
var angle = rn(110, 359);
arr = [].concat(arr, [{
color: 'rgba(81, 180, 200, 0.5)',
distortion: rn(15, 75),
tmod: rn(5, 10),
size: rn(15, 20),
speed: 0.0005,
angle: angle,
lastPos: {
x: w / 2,
y: h / 2
}
}]);
}
var draw = function draw() {
request = requestAnimationFrame(function () {
return draw();
});
t++;
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0,.1)';
ctx.fillRect(0, 0, w, h);
var crad = rad * Math.sin(300);
ctx.globalCompositeOperation = 'lighter';
arr.forEach(function (el) {
ctx.strokeStyle = el.color;
ctx.lineWidth = el.size;
ctx.beginPath();
var lastPos = el.angle - 0.0005;
var x = w / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.cos(el.angle * 180 / Math.PI);
var y = h / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.sin(el.angle * 180 / Math.PI);
ctx.moveTo(el.lastPos.x, el.lastPos.y);
ctx.lineTo(x, y);
el.lastPos = { x: x, y: y };
el.angle = (el.angle + 0.0005) % 359;
ctx.stroke();
});
};
var resize = function resize() {
iso.width = w = window.innerWidth;
iso.height = h = window.innerHeight;
};
var request = requestAnimationFrame(function () {
return draw();
});
window.addEventListener('resize', function () {
return resize();
});
</script>
<script>
$(\"#loghold\").hide();
</script>
";
}else{
echo "<script>
'use strict';
var rn = function rn(min, max) {
return Math.random() * (max - min) + min;
};
var ctx = iso.getContext('2d');
var _window = window;
var w = _window.innerWidth;
var h = _window.innerHeight;
var t = 10;
var arr = [];
var cn = 200;
var rad = 300;
iso.width = w;
iso.height = h;
while (~ ~ cn--) {
var angle = rn(110, 359);
arr = [].concat(arr, [{
color: 'rgba(255, 255, 255, 0.5)',
distortion: rn(15, 75),
tmod: rn(5, 10),
size: rn(15, 20),
speed: rn(1, 5) / 5000,
angle: angle,
lastPos: {
x: w / 2,
y: h / 2
}
}]);
}
var draw = function draw() {
request = requestAnimationFrame(function () {
return draw();
});
t++;
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0,.1)';
ctx.fillRect(0, 0, w, h);
var crad = rad * Math.sin(300);
ctx.globalCompositeOperation = 'lighter';
arr.forEach(function (el) {
ctx.strokeStyle = el.color;
ctx.lineWidth = el.size;
ctx.beginPath();
var lastPos = el.angle - el.speed;
var x = w / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.cos(el.angle * 180 / Math.PI);
var y = h / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.sin(el.angle * 180 / Math.PI);
ctx.moveTo(el.lastPos.x, el.lastPos.y);
ctx.lineTo(x, y);
el.lastPos = { x: x, y: y };
el.angle = (el.angle + el.speed) % 359;
ctx.stroke();
});
};
var resize = function resize() {
iso.width = w = window.innerWidth;
iso.height = h = window.innerHeight;
};
var request = requestAnimationFrame(function () {
return draw();
});
window.addEventListener('resize', function () {
return resize();
});
</script>
";
};
?>
ajax in php
echo " <script>
$(\"#isoholder\").load(\"/iso/iso.php\");
</script>";
Change the page to have the javascript for animation outside the session condition and in the session code just flag via a global var that you are logged in
... page data
<script>
// the following var must be global to the page.
var sessionLoggedIn = false; // use this to determine the colours to use
// the code to do the animation
...
function draw(){
if(sessionLoggedIn){ // if true then logged in
}else{ // not logged in
}
}
</script>
<?php
session_start();
if (isset($_SESSION['userid'])){
$userid = $_SESSION['userid'];
echo " <script> sessionLoggedIn = true;</script> ";
}else{
echo "<script> sessionLoggedIn = false;</script> ";
}
?>
Related
I have a simple app to create a canvas and render it. I am using capture js and FFmpeg module for converting videos in my app, but when I run the app I get the following reference error:
Uncaught ReferenceError: CCapture is not defined
at test.js:67`
Here is test.js:
(function() {
"use strict";
var framesPerSecond = 60;
var numFrames = 20; //framesPerSecond * 60 * 2;
var thickness = 100;
var speed = 4;
var frameNum = 0;
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
canvas.width = 1280;
canvas.height = 720;
var progressElem = document.getElementById("progress");
var progressNode = document.createTextNode("");
progressElem.appendChild(progressNode);
function onProgress(progress) {
progressNode.nodeValue = (progress * 100).toFixed(1) + "%";
}
function showVideoLink(url, size) {
size = size ? (" [size: " + (size / 1024 / 1024).toFixed(1) + "meg]") : " [unknown size]";
var a = document.createElement("a");
a.href = url;
var filename = url;
var slashNdx = filename.lastIndexOf("/");
if (slashNdx >= 0) {
filename = filename.substr(slashNdx + 1);
}
a.download = filename;
a.appendChild(document.createTextNode(url + size));
document.body.appendChild(a);
}
var capturer = new CCapture( {
format: 'ffmpegserver',
//workersPath: "3rdparty/",
//format: 'gif',
verbose: false,
framerate: framesPerSecond,
onProgress: onProgress,
//extension: ".mp4",
//codec: "libx264",
} );
capturer.start();
function drawLines(ctx) {
for (var xx = -canvas.width; xx < canvas.width; xx += 2) {
var l = (xx - (-canvas.width)) / (canvas.width * 2);
ctx.beginPath();
ctx.moveTo(xx, -canvas.height);
ctx.lineTo(xx, canvas.height);
ctx.strokeStyle = "hsla(" + ((l * 360 * 24) % 360) + ",100%,50%,0.5)";
ctx.stroke();
}
}
function render(time) {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#FFF";
for (var xx = 0; xx < canvas.width + thickness * 2; xx += thickness * 2) {
var x = xx - (frameNum * speed % (thickness * 2));
ctx.fillRect(x, 0, thickness, canvas.height);
}
ctx.save();
ctx.globalCompositeOperation = "difference";
ctx.font = "400px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(frameNum, canvas.width / 2, canvas.height / 2);
ctx.save();
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(frameNum * 0.01);
ctx.translate(canvas.width * 0.25, 0);
drawLines(ctx);
ctx.restore();
ctx.save();
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(frameNum * -0.013);
ctx.translate(canvas.width * 0.37, 0);
drawLines(ctx);
ctx.restore();
ctx.restore();
capturer.capture(canvas);
++frameNum;
if (frameNum === numFrames) {
capturer.stop();
capturer.save(showVideoLink);
} else {
requestAnimationFrame(render);
}
}
requestAnimationFrame(render);
}());
How would I go about changing a defined variable in a js script that is running when a specific php session variable response is returned?
How would I change the color within this canvas js array when a specific php session variable is set. The method I am using now is leading to a problem of increasing the speed of the animation though the color does change.
<div id="isohold">
<canvas id="iso"></canvas>
<div id="loghold">Login</div>
</div>
<?php
session_start();
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['userid'])){
$userid = $_SESSION['userid'];
echo " <script>
'use strict';
var rn = function rn(min, max) {
return Math.random() * (max - min) + min;
};
var ctx = iso.getContext('2d');
var _window = window;
var w = _window.innerWidth;
var h = _window.innerHeight;
var t = 10;
var arr = [];
var cn = 200;
var rad = 300;
var sp = rn(1, 5) / 10000;
iso.width = w;
iso.height = h;
while (~ ~ cn--) {
var angle = rn(110, 359);
arr = [].concat(arr, [{
color: 'rgba(81, 180, 200, 0.5)',
distortion: rn(15, 75),
tmod: rn(5, 10),
size: rn(15, 20),
speed: 0.0005,
angle: angle,
lastPos: {
x: w / 2,
y: h / 2
}
}]);
}
var draw = function draw() {
request = requestAnimationFrame(function () {
return draw();
});
t++;
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0,.1)';
ctx.fillRect(0, 0, w, h);
var crad = rad * Math.sin(300);
ctx.globalCompositeOperation = 'lighter';
arr.forEach(function (el) {
ctx.strokeStyle = el.color;
ctx.lineWidth = el.size;
ctx.beginPath();
var lastPos = el.angle - 0.0005;
var x = w / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.cos(el.angle * 180 / Math.PI);
var y = h / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.sin(el.angle * 180 / Math.PI);
ctx.moveTo(el.lastPos.x, el.lastPos.y);
ctx.lineTo(x, y);
el.lastPos = { x: x, y: y };
el.angle = (el.angle + 0.0005) % 359;
ctx.stroke();
});
};
var resize = function resize() {
iso.width = w = window.innerWidth;
iso.height = h = window.innerHeight;
};
var request = requestAnimationFrame(function () {
return draw();
});
window.addEventListener('resize', function () {
return resize();
});
</script>
<script>
$(\"#loghold\").hide();
</script>
";
}else{
echo "<script>
'use strict';
var rn = function rn(min, max) {
return Math.random() * (max - min) + min;
};
var ctx = iso.getContext('2d');
var _window = window;
var w = _window.innerWidth;
var h = _window.innerHeight;
var t = 10;
var arr = [];
var cn = 200;
var rad = 300;
iso.width = w;
iso.height = h;
while (~ ~ cn--) {
var angle = rn(110, 359);
arr = [].concat(arr, [{
color: 'rgba(255, 255, 255, 0.5)',
distortion: rn(15, 75),
tmod: rn(5, 10),
size: rn(15, 20),
speed: rn(1, 5) / 5000,
angle: angle,
lastPos: {
x: w / 2,
y: h / 2
}
}]);
}
var draw = function draw() {
request = requestAnimationFrame(function () {
return draw();
});
t++;
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0,.1)';
ctx.fillRect(0, 0, w, h);
var crad = rad * Math.sin(300);
ctx.globalCompositeOperation = 'lighter';
arr.forEach(function (el) {
ctx.strokeStyle = el.color;
ctx.lineWidth = el.size;
ctx.beginPath();
var lastPos = el.angle - el.speed;
var x = w / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.cos(el.angle * 180 / Math.PI);
var y = h / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.sin(el.angle * 180 / Math.PI);
ctx.moveTo(el.lastPos.x, el.lastPos.y);
ctx.lineTo(x, y);
el.lastPos = { x: x, y: y };
el.angle = (el.angle + el.speed) % 359;
ctx.stroke();
});
};
var resize = function resize() {
iso.width = w = window.innerWidth;
iso.height = h = window.innerHeight;
};
var request = requestAnimationFrame(function () {
return draw();
});
window.addEventListener('resize', function () {
return resize();
});
</script>
";
};
?>
<?php $color="yellow"; ?> <!--define it in php-->
<div id="color" data-color= <?php echo $color; ?> ></div> <!--insert it in html-->
<script>
var color=""; //declare your variable in JS
window.onload = function(e) {
color=document.getElementById("color").dataset.color; //redefine the variable's value from the html defined by the php
};
</script>
I am trying to create a blackhole simulation, where all the balls that are outside of it go away from it at a given speed and those that fall on it are dragged towards the circle until they reach the center of it, where they would stop and disappear, here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blackhole simulation escape velocity</title>
<script>
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs-5 ) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D (0,0);
var forceDirection2 = Math.atan2(pos.y - 400, pos.x - 700);
var g = (pixel_G*pixel_M)/(distance*distance*1e2);
delta2.x += Math.cos(forceDirection2)*g;
delta2.y += Math.sin(forceDirection2)*g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == 700 && pos.y == 400){
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, { x: 700,
y: 400 }, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c=parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick (){
canvas = document.getElementById ('space');
ctx = canvas.getContext ('2d')
canvas.addEventListener ("mousedown", init, false)
blackhole = new Ball (5, {x: 700,
y: 400 }, 0);
blackhole.draw (ctx) ;
}
window.onload = onClick;
</script>
<style>
body {
background-color:#021c36 ;
margin: 0px;
}
</style>
</head>
<body>
<canvas id = "space", width = "1400", height = "800">
</canvas>
</body>
</html>
Now as you can see, I created a second variable called delta2, but the problem is that it can't update the position of the circles, which in term makes it impossible to move the circle, can someone tell me what is wrong. Also, how can I make the big black circle after a certain amount of time, i know i probably should create a timer, but i don't know how they work
The gravity is too weak. I put a pseudo gravity to demonstrate.
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var bh = {
w:500,
h:300
};
bh.cx = Math.floor(bh.w/2);
bh.cy = Math.floor(bh.h/2)
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - bh.cx) * (pos.x - bh.cx)) + ((pos.y - bh.cy) * (pos.y - bh.cy)));
if (distance > pixel_Rs - 5) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
var delta2 = new Vector2D(0, 0);
var forceDirection2 = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
// FIX THIS!!!
var g = 1;//(pixel_G * pixel_M) / (distance * distance * 1e2);
delta2.x += Math.cos(forceDirection2) * g;
delta2.y += Math.sin(forceDirection2) * g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == bh.cx && pos.y == bh.cy) {
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
canvas.width = bh.w;
canvas.height = bh.h;
ctx = canvas.getContext('2d');
blackhole = new Ball(5, { //pixel_Rs, {
x: bh.cx,
y: bh.cy
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * bh.w), Math.floor(Math.random() * bh.h));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
var c = parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
function onClick() {
canvas = document.getElementById('space');
ctx = canvas.getContext('2d')
canvas.addEventListener("mousedown", init, false)
blackhole = new Ball(5, {
x: bh.cx,
y: bh.cy
}, 0);
blackhole.draw(ctx);
}
window.onload = onClick;
body {
background-color: #021c36;
margin: 0px;
}
<canvas id="space" , width="700" , height="400"></canvas>
I made this (run snippet below)
var Canvas = document.getElementById('c');
var ctx = Canvas.getContext('2d');
var resize = function() {
Canvas.width = Canvas.clientWidth;
Canvas.height = Canvas.clientHeight;
};
window.addEventListener('resize', resize);
resize();
var elements = [];
var presets = {};
presets.shard = function (x, y, s, random, color) {
return {
x: x,
y: y,
draw: function(ctx, t) {
this.x += 0;
this.y += 0;
var posX = this.x + + Math.sin((50 + x + (t / 10)) / 100) * 5;
var posy = this.y + + Math.sin((55 + x + (t / 10)) / 100) * 7;
ctx.beginPath();
ctx.fillStyle = color;
ctx.moveTo(posX, posy);
ctx.lineTo(posX+random,posy+random);
ctx.lineTo(posX+random,posy+random);
ctx.lineTo(posX+0,posy+50);
ctx.closePath();
ctx.fill();
}
}
};
for(var x = 0; x < Canvas.width; x++) {
for(var y = 0; y < Canvas.height; y++) {
if(Math.round(Math.random() * 60000) == 1) {
var s = ((Math.random() * 5) + 1) / 10;
if(Math.round(Math.random()) == 1){
var random = Math.floor(Math.random() * 100) + 10;
var colorRanges = ['#8c8886', '#9c9995'];
var color = colorRanges[Math.floor(Math.random() * colorRanges.length)];
elements.push(presets.shard(x, y, s, random, color));
}
}
}
}
setInterval(function() {
ctx.clearRect(0, 0, Canvas.width, Canvas.height);
var time = new Date().getTime();
for (var e in elements)
elements[e].draw(ctx, time);
}, 10);
<canvas id="c" width="1000" height="1000"\>
I just need to add one feature to be able to use it on the site I'm building it for. Some of the floating shards need to be blurred to give a sense of depth.
Can Canvas do this, and if so, how?
context.filter = 'blur(10px)';
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
I used this few months ago, maybe it could work for you as well :
var canvas = document.getElementById("heroCanvas");
var canvasContext = canvas.getContext("2d");
var canvasBackground = new Image();
canvasBackground.src = "image.jpg";
var drawBlur = function() {
// Store the width and height of the canvas for below
var w = canvas.width;
var h = canvas.height;
// This draws the image we just loaded to our canvas
canvasContext.drawImage(canvasBackground, 0, 0, w, h);
// This blurs the contents of the entire canvas
stackBlurCanvasRGBA("heroCanvas", 0, 0, w, h, 100);
}
canvasBackground.onload = function() {
drawBlur();
}
Here the source : http://zurb.com/playground/image-blur-texture
I'm using this jsfiddle for the animation and the final value is
wheel.segments[i]
http://jsfiddle.net/bramp/94jP6/
And I would like to retrieve that value after animation has stopped so I can use it in PHP. I tried something like:
function retrivewinner() {
var winner = wheel.segments[i];
window.location.href = "index.php?tag=" + winner;
}
But it would freeze the browser or reload each time
i have edit your code, try:
// Helpers
shuffle = function(o) {
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
String.prototype.hashCode = function() {
// See http://www.cse.yorku.ca/~oz/hash.html
var hash = 5381;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash << 5) + hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
// List of venues. These are foursquare IDs, with the idea that eventually it'll tie in
venues = {
"116208": "Jerry's Subs and Pizza",
"66271": "Starbucks",
"5518": "Ireland's Four Courts",
"392360": "Five Guys",
"2210952": "Uptown Cafe",
"207306": "Corner Bakery Courthouse",
"41457": "Delhi Dhaba",
"101161": "TNR Cafe",
"257424": "Afghan Kabob House",
"512060": "The Perfect Pita",
"66244": "California Tortilla",
"352867": "Pho 75 - Rosslyn",
"22493": "Ragtime",
"268052": "Subway",
"5665": "Summers Restaurant & Sports Bar",
"129724": "Cosi",
"42599": "Ray's Hell Burger"
};
$(function() {
var venueContainer = $('#venues ul'),
e_winner = null;
$.each(venues, function(key, item) {
venueContainer.append(
$(document.createElement("li")).append(
$(document.createElement("input")).attr({
id: 'venue-' + key,
name: item,
value: item,
type: 'checkbox',
checked: true
}).change(function() {
var cbox = $(this)[0];
var segments = wheel.segments;
var i = segments.indexOf(cbox.value);
if (cbox.checked && i == -1) {
segments.push(cbox.value);
} else if (!cbox.checked && i != -1) {
segments.splice(i, 1);
}
segments.sort();
wheel.update();
})
).append(
$(document.createElement('label')).attr({
'for': 'venue-' + key
}).text(item)))
});
$('#venues ul>li').tsort("input", {
attr: "value"
});
});
// WHEEL!
var wheel = {
timerHandle: 0,
timerDelay: 33,
angleCurrent: 0,
angleDelta: 0,
size: 290,
canvasContext: null,
colors: ['#ffff00', '#ffc700', '#ff9100', '#ff6301', '#ff0000', '#c6037e',
'#713697', '#444ea1', '#2772b2', '#0297ba', '#008e5b', '#8ac819'],
segments: [],
seg_colors: [],
// Cache of segments to colors
maxSpeed: Math.PI / 16,
upTime: 1000,
// How long to spin up for (in ms)
downTime: 17000,
// How long to slow down for (in ms)
spinStart: 0,
frames: 0,
centerX: 300,
centerY: 300,
spin: function() {
// Start the wheel only if it's not already spinning
if (wheel.timerHandle == 0) {
wheel.spinStart = new Date().getTime();
wheel.maxSpeed = Math.PI / (16 + Math.random()); // Randomly vary how hard the spin is
wheel.frames = 0;
wheel.sound.play();
wheel.timerHandle = setInterval(wheel.onTimerTick, wheel.timerDelay);
}
},
onTimerTick: function() {
wheel.frames++;
wheel.draw();
var duration = (new Date().getTime() - wheel.spinStart);
var progress = 0;
var finished = false;
if (duration < wheel.upTime) {
progress = duration / wheel.upTime;
wheel.angleDelta = wheel.maxSpeed * Math.sin(progress * Math.PI / 2);
} else {
progress = duration / wheel.downTime;
wheel.angleDelta = wheel.maxSpeed * Math.sin(progress * Math.PI / 2 + Math.PI / 2);
if (progress >= 1) finished = true;
}
wheel.angleCurrent += wheel.angleDelta;
while (wheel.angleCurrent >= Math.PI * 2)
// Keep the angle in a reasonable range
wheel.angleCurrent -= Math.PI * 2;
if (finished) {
clearInterval(wheel.timerHandle);
wheel.timerHandle = 0;
wheel.angleDelta = 0;
$("#counter").html((wheel.frames / duration * 1000) + " FPS");alert(e_winner);
// here you build a post or get request $.post('save.php',{value:e_winner});
}
/*
// Display RPM
var rpm = (wheel.angleDelta * (1000 / wheel.timerDelay) * 60) / (Math.PI * 2);
$("#counter").html( Math.round(rpm) + " RPM" );
*/
},
init: function(optionList) {
try {
wheel.initWheel();
wheel.initAudio();
wheel.initCanvas();
wheel.draw();
$.extend(wheel, optionList);
} catch (exceptionData) {
alert('Wheel is not loaded ' + exceptionData);
}
},
initAudio: function() {
var sound = document.createElement('audio');
sound.setAttribute('src', 'http://bramp.net/javascript/wheel.mp3');
wheel.sound = sound;
},
initCanvas: function() {
var canvas = $('#wheel #canvas').get(0);
if ($.browser.msie) {
canvas = document.createElement('canvas');
$(canvas).attr('width', 1000).attr('height', 600).attr('id', 'canvas').appendTo('.wheel');
canvas = G_vmlCanvasManager.initElement(canvas);
}
canvas.addEventListener("click", wheel.spin, false);
wheel.canvasContext = canvas.getContext("2d");
},
initWheel: function() {
shuffle(wheel.colors);
},
// Called when segments have changed
update: function() {
// Ensure we start mid way on a item
//var r = Math.floor(Math.random() * wheel.segments.length);
var r = 0;
wheel.angleCurrent = ((r + 0.5) / wheel.segments.length) * Math.PI * 2;
var segments = wheel.segments;
var len = segments.length;
var colors = wheel.colors;
var colorLen = colors.length;
// Generate a color cache (so we have consistant coloring)
var seg_color = new Array();
for (var i = 0; i < len; i++)
seg_color.push(colors[segments[i].hashCode().mod(colorLen)]);
wheel.seg_color = seg_color;
wheel.draw();
},
draw: function() {
wheel.clear();
wheel.drawWheel();
wheel.drawNeedle();
},
clear: function() {
var ctx = wheel.canvasContext;
ctx.clearRect(0, 0, 1000, 800);
},
drawNeedle: function() {
var ctx = wheel.canvasContext;
var centerX = wheel.centerX;
var centerY = wheel.centerY;
var size = wheel.size;
ctx.lineWidth = 1;
ctx.strokeStyle = '#000000';
ctx.fileStyle = '#ffffff';
ctx.beginPath();
ctx.moveTo(centerX + size - 40, centerY);
ctx.lineTo(centerX + size + 20, centerY - 10);
ctx.lineTo(centerX + size + 20, centerY + 10);
ctx.closePath();
ctx.stroke();
ctx.fill();
// Which segment is being pointed to?
var i = wheel.segments.length - Math.floor((wheel.angleCurrent / (Math.PI * 2)) * wheel.segments.length) - 1;
// Now draw the winning name
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = '#000000';
ctx.font = "2em Arial";
ctx.fillText(wheel.segments[i], centerX + size + 25, centerY);e_winner= wheel.segments[i];
},
drawSegment: function(key, lastAngle, angle) {
var ctx = wheel.canvasContext;
var centerX = wheel.centerX;
var centerY = wheel.centerY;
var size = wheel.size;
var segments = wheel.segments;
var len = wheel.segments.length;
var colors = wheel.seg_color;
var value = segments[key];
ctx.save();
ctx.beginPath();
// Start in the centre
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, size, lastAngle, angle, false); // Draw a arc around the edge
ctx.lineTo(centerX, centerY); // Now draw a line back to the centre
// Clip anything that follows to this area
//ctx.clip(); // It would be best to clip, but we can double performance without it
ctx.closePath();
ctx.fillStyle = colors[key];
ctx.fill();
ctx.stroke();
// Now draw the text
ctx.save(); // The save ensures this works on Android devices
ctx.translate(centerX, centerY);
ctx.rotate((lastAngle + angle) / 2);
ctx.fillStyle = '#000000';
ctx.fillText(value.substr(0, 20), size / 2 + 20, 0);
ctx.restore();
ctx.restore();
},
drawWheel: function() {
var ctx = wheel.canvasContext;
var angleCurrent = wheel.angleCurrent;
var lastAngle = angleCurrent;
var segments = wheel.segments;
var len = wheel.segments.length;
var colors = wheel.colors;
var colorsLen = wheel.colors.length;
var centerX = wheel.centerX;
var centerY = wheel.centerY;
var size = wheel.size;
var PI2 = Math.PI * 2;
ctx.lineWidth = 1;
ctx.strokeStyle = '#000000';
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.font = "1.4em Arial";
for (var i = 1; i <= len; i++) {
var angle = PI2 * (i / len) + angleCurrent;
wheel.drawSegment(i - 1, lastAngle, angle);
lastAngle = angle;
}
// Draw a center circle
ctx.beginPath();
ctx.arc(centerX, centerY, 20, 0, PI2, false);
ctx.closePath();
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = '#000000';
ctx.fill();
ctx.stroke();
// Draw outer circle
ctx.beginPath();
ctx.arc(centerX, centerY, size, 0, PI2, false);
ctx.closePath();
ctx.lineWidth = 10;
ctx.strokeStyle = '#000000';
ctx.stroke();
},
}
window.onload = function() {
wheel.init();
var segments = new Array();
$.each($('#venues input:checked'), function(key, cbox) {
segments.push(cbox.value);
});
wheel.segments = segments;
wheel.update();
// Hide the address bar (for mobile devices)!
setTimeout(function() {
window.scrollTo(0, 1);
}, 0);
}