var imagething;
var kernel = [[1, 2, 1], [2, 4, 2], [1, 2, 1]];
var sum_of_elements = 0;
var mult_factor = 0.0625;
var bias = 0;
function preload() {
imagething = loadImage('data/image.png');
}
function setup() {
createCanvas(1000, 1000);
imagething.loadPixels();
image(imagething, 0, 0);
makeBlurred(imagething, 1);
image(imagething, 512, 0);
}
function imageIndex(img, x, y) {
return 4 * (x + y * img.width);
}
function makeBlurred() {
for(var i = 0; i < kernel.length; i++) {
for(var j = 0; j < kernel.length; j++) {
sum_of_elements += kernel[i][j];
}
}
for(var x = 0; x < imagething.width; x++) {
for(var y = 0; y < imagething.height; y++) {
var red = 0;
var green = 0;
var blue = 0;
for(var i = 0; i < kernel.length; i++) {
for(var j = 0; j < kernel.length; j++) {
var imageX = (x - kernel.length / 2 + i + imagething.width) % imagething.width;
var imageY = (y - kernel.length / 2 + j + imagething.height) % imagething.height;
var RGB = imageIndex(imagething, imageX, imageY);
var pix = imagething.pixels;
var R = pix[RGB];
var G = pix[RGB + 1];
var B = pix[RGB + 2];
console.log("Start: ",R,G,B);
red += (R * kernel[i][j]);
green += (G * kernel[i][j]);
blue += (B * kernel[i][j]);
}
}
var outR;
var outG;
var outB;
outR = Math.min(Math.max(Math.round(red * mult_factor), 0), 255);
outG = Math.min(Math.max(Math.round(green * mult_factor), 0), 255);
outB = Math.min(Math.max(Math.round(blue * mult_factor), 0), 255);
console.log("End: ", outR, outG, outB);
pix[RGB] = outR;
pix[RGB + 1] = outG;
pix[RGB + 2] = outB;
imagething.updatePixels();
}
}
}
So I am referencing this blog post on kernel-based image processing and I am trying to blur my image. I am using the blur matrix and I use the original image and it should turn out like this but it ends up like this so I must be doing something wrong. Help is much appreciated :)
Related
webpack and babylon.js is not loading images, videos and models. How can i fix that ?
I have already tried to do this
BABYLON.SceneLoader.ImportMesh("him", "Dude/", "dude.babylon", scene, function (newMeshes, particleSystems, skeletons) {
newMeshes[0].position = new BABYLON.Vector3(0, 0, 5); // The original dude
scene.beginAnimation(skeletons[0], 0, 120, 1.0, true);
dudes = [];
for (i = 0; i < 10; i++) { // 10 clones
var xrand = Math.floor(Math.random() * 501) - 250;
var zrand = Math.floor(Math.random() * 501) - 250;
var c = [];
for (j = 1; j < newMeshes.length; j++) {
c[j] = newMeshes[j].clone("c" + j);
c[j].position = new BABYLON.Vector3(xrand, 0, zrand);
c[j].skeleton = newMeshes[j].skeleton.clone();
scene.beginAnimation(c[j].skeleton, 0, 120, 1.0, true);
}
dudes[i] = c;
}
This function shuffles only matrix[y], but I want it to shuffle matrix[y][x] But it doesn't want to shuffle correctly.
The code what I used:
function Shuffle(arguments) {
for (var k = 0; k < arguments.length; k++) {
var i = arguments[k].length;
if (i == 0)
return false;
else {
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = arguments[k][i];
var tempj = arguments[k][j];
arguments[k][i] = tempj;
arguments[k][j] = tempi;
}
return arguments;
}
}
return arguments
}
var matrix = [
];
var ab = 36;
for (var y = 0; y < ab; y++) {
matrix.push([])
for (var x = 0; x < ab; x++) {
matrix[y][x] = Math.floor(Math.random() * 1)
}
for (var x = 0; x < ab / 2; x++) {
matrix[y][x] = 1
}
}
arr = Shuffle(matrix);
console.log(arr)
var side = 16;
function setup() {
createCanvas(arr[0].length * side, arr.length * side);
background('#acacac');
frameRate()
}
function draw() {
for (var y = 0; y < arr.length; y++) {
for (var x = 0; x < arr[y].length; x++) {
if (matrix[y][x] == 0) {
fill(0, 255, 0)
rect(y * side, x * side, side, side)
} else if (matrix[y][x] == 1) {
fill("red")
rect(y * side, x * side, side, side)
} else if (matrix[y][x] == 2) {
fill(255, 255, 0)
rect(y * side, x * side, side, side)
} else if (matrix[y][x] == 3) {
fill(255, 0, 0)
rect(y * side, x * side, side, side)
}
}
}
}
So this function shuffles only matrix[y], but I want it to shuffle matrix[y][x].
Any ideas? Here is the screenshot:
.
As mentioned in comment, you had a return statement after the whileloop, causing the forloop to never finish as expected
function Shuffle(arguments) {
for (var k = 0; k < arguments.length; k++) {
var i = arguments[k].length;
if (i == 0)
return false;
else {
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = arguments[k][i];
var tempj = arguments[k][j];
arguments[k][i] = tempj;
arguments[k][j] = tempi;
}
return arguments; // remove this line
}
}
return arguments
}
You probably can transform this to a one dimensional array, then shuffle, then transform back. You just need to know how many rows you want.
const myArr = [[1,2],[3,4]];
const oneDimArr = myArr.reduce((a, b) => [...a, ...b], []);
const shuffledArr = Shuffle(oneDimArr); // this is your existing function
const shuffled2DimArr = shuffledArr.reduce((acc, i) => {
if(acc[acc.length-1].length >= 2) { // here we build 2 cols
acc.push([]);
}
acc[acc.length-1].push(i);
return acc;
}, [[]]);
Here's my code
const arrayColumn = (arr, n) => arr.map(x => x[n]);
const pcorr = (x, y) => {
let sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0,
sumY2 = 0;
const minLength = x.length = y.length = Math.min(x.length, y.length),
reduce = (xi, idx) => {
const yi = y[idx];
sumX += xi;
sumY += yi;
sumXY += xi * yi;
sumX2 += xi * xi;
sumY2 += yi * yi;
}
x.forEach(reduce);
return (minLength * sumXY - sumX * sumY) / Math.sqrt((minLength * sumX2 - sumX * sumX) * (minLength * sumY2 - sumY * sumY));
};
//create pearson correlation matrix
var r = [[]];
var r_temp = [];
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
}
}
var r_temp_length = r_temp.length;
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
r_temp_length = r_temp_length - 1;
}
}
_arrData is the data from .csv file that already read as matrix 43X4
r_temp result is
[1, 0.1001546791334383, -0.09722360940329312, -0.1119017933192886, 0.1001546791334383, 1, 0.19766088533723247, -0.03844791092325515, -0.09722360940329312, 0.19766088533723247, 1, -0.06161560854254137, -0.1119017933192886, -0.03844791092325515, -0.06161560854254137, 1]
r_temp length is 16
I want to input the r_temp value into r which is gonna be 4x4 Matrix
When I run this code, there's error from this part
r[i - 1][j - 1] = r_temp[_arrData[0].length^2 - r_temp_length];
Uncaught TypeError: Cannot set property '0' of undefined
var r = [];
...
for (var i = 1; i <= _arrData[0].length; i++) {
r[i - 1] = [];
....
It should be var r = []; instead of [[]].
In your code the line r[i - 1] = []; is missing.
It creates the second array for r[i - 1].
thank you all, it works!
//create pearson correlation matrix
var r = [];
for (var i = 1; i <= _arrData[0].length; i++) {
r[i - 1] = [];
}
var r_temp = [];
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r_temp.push(pcorr(arrayColumn(_arrData,i-1),arrayColumn(_arrData,j-1)));
}
}
var r_temp_length = r_temp.length;
for (var i = 1; i <= _arrData[0].length; i++) {
for (var j = 1; j <= _arrData[0].length; j++) {
r[i - 1][j - 1] = r_temp[Math.pow(_arrData[0].length,2) - r_temp_length];
r_temp_length = r_temp_length - 1;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have an array with strings that I would like to traverse diagonally.
Assumptions:
Each string is the same length.
Arrays could be square or rectangular, horizontally or vertically.
The matrix looks like this:
A B C D
E F G H
I J K L
I Would like to get (from top left to bottom right):
A
EB
IFC
JGD
KH
L
and (from the bottom left to top right):
I
JE
KFA
LGB
HC
D
I already have a piece of code that works 3/4 of the way, but i cant seem to figure out what I am doing (wrong).
//the array
var TheArray = ['ABCD','EFGH','IJKL'];
//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;
The code I have chops up the diagonals into 4 of these loops to get all the diagonals. It looks as 2 for loops with an if to not loop over unbound values. The pseudo code looks a bit like this:
for(loop rows){
var outputarray = [];
for(loop columns){
if(delimit for out of bound){
var temprow = TheArray[something?];
var tempvalue = temprow[something?];
outputarray.push(tempvalue);
}
}
//use values
document.getElementById("theDiv").innerHTML += outputarray.join("")+"<br>";
}
I hope somebody can help me with this.
From top left to bottom right
var theArray = ["ABCD","EFGH","IJKL"];
var length = { "x" : theArray[0].length, "y" : theArray.length };
length.max = Math.max(length.x, length.y);
var temp, k, x, y;
for (k = 0; k <= 2 * (length.max - 1); ++k) {
for (temp = [], y = length.y - 1; (x = k - y), y >= 0; --y) {
x >= 0 && x < length.x && temp.push(theArray[y][x]);
}
temp.length > 0 && (document.body.innerHTML += temp.join('') + '<br>');
}
(see also this Fiddle)
From the bottom left to top right
var theArray = ["ABCD","EFGH","IJKL"];
var length = { "x" : theArray[0].length, "y" : theArray.length };
length.max = Math.max(length.x, length.y);
var temp, k, x, y;
for (k = 0; k <= 2 * (length.max - 1); ++k) {
for (temp = [], y = length.y - 1; (x = k + y - length.y), y >= 0; --y) {
x >= 0 && x < length.x && temp.push(theArray[y][x]);
}
temp.length > 0 && (document.body.innerHTML += temp.join('') + '<br>');
}
(see also this Fiddle)
Combined
As there's but a single line of difference between both, you can easily combine them in a single function :
var theArray = ["ABCD","EFGH","IJKL"];
function diagonal(data, fromBottom) {
var length = { "x" : data[0].length, "y" : data.length };
length.max = Math.max(length.x, length.y);
var temp, k, x, y;
var returnMe = [];
for (k = 0; k <= 2 * (length.max - 1); ++k) {
for (temp = [], y = length.y - 1; y >= 0; --y) {
x = k - (fromBottom ? length.y - y : y);
x >= 0 && x < length.x && temp.push(data[y][x]);
}
temp.length > 0 && returnMe.push(temp.join(''));
}
return returnMe;
}
document.body.innerHTML = diagonal(theArray).join('<br>') +
'<br><br><br>' +
diagonal(theArray, true).join('<br>');
(see also this Fiddle)
This does the trick, and outputs the desired results to the screen:
var array = ['ABCD','EFGH','IJKL'];
var rows = array.length;
var cols = array[0].length;
for (var n = 0; n < cols + rows - 1; n += 1)
{
var r = n;
var c = 0;
var str = '';
while (r >= 0 && c < cols)
{
if (r < rows)
str += array[r][c];
r -= 1;
c += 1;
}
document.write(str+"<br>");
}
Result:
A
EB
IFC
JGD
KH
L
Yet another solution:
function getAllDiagonal(array) {
function row(offset) {
var i = array.length, a = '';
while (i--) {
a += array[i][j + (offset ? offset - i : i)] || '';
}
return a;
}
var result = [[], []], j;
for (j = 1 - array.length; j < array[0].length; j++) {
result[0].push(row(0));
result[1].push(row(array.length - 1));
}
return result;
}
var array = ['ABCD', 'EFGH', 'IJKL'];
document.write('<pre>' + JSON.stringify(getAllDiagonal(array), 0, 4) + '</pre>');
Use indices:
[i][j-i]
Where i goes from 0 to M-1
j goes from 0 to i
While j++ < N
for the matrix
type Array[M][N]
However this may miss a few at the bottom right if the matrix is rectangular, and you might need a second nested for loop with i and j to capture those.
Try this
var TheArray = ['ABCD', 'EFGH', 'IJKL'];
//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;
var totalNoComb = RowLength + ColumnLength - 1;
var combArr = new Array(totalNoComb);
for (var i = 0; i < totalNoComb; i++) {
combArr[i] = "";
for (var j = RowLength-1; j >-1; j--) {
if (i - j > -1 && i - j < ColumnLength)
combArr[i] += TheArray[j][i-j];
}
}
alert(combArr);
for (var i = 0; i < totalNoComb; i++) {
combArr[i] = "";
for (var j = 0; j < RowLength; j++) {
if (i - j > -1 && i - j < ColumnLength)
combArr[i] += TheArray[ RowLength -1-j][i - j];
}
}
alert(combArr);
This should work even for rectangular matrices:
var array = ["ABCD", "EFGH", "IJKL"];
var arrOfArr = [];
var resultArray = [];
for (var i = 0; i < array.length; ++i) {
arrOfArr.push(array[i].split(''));
}
var rows = arrOfArr.length;
var columns = arrOfArr[0].length;
var index = 0;
for (var i = 0; i < rows; ++i) {
var k = 0;
resultArray[index] = new Array();
for (var j = i; j >= 0; --j) {
resultArray[index].push(arrOfArr[j][k]);
++k;
if ( k === columns) {
break;
}
}
resultArray[index] = resultArray[index].join('');
++index;
}
for (var j = 1; j < columns; ++j) {
var k = rows - 1;
resultArray[index] = new Array();
for (var i = j; i < columns; ++i) {
resultArray[index].push(arrOfArr[k][i]);
--k;
if ( k === -1) {
break;
}
}
resultArray[index] = resultArray[index].join('');
++index;
}
console.log(JSON.stringify(resultArray));
Note: This assumes that all strings are the same size, or at least are as large as the first string.
In a 2D array (or in this case, an array of strings), a diagonal's indexes add up to the diagonal's number (like a row-number). 00, 01 10, 02 11 20, etc.
Using this method, the number of diagonal "rows" (starting at zero) is equal to the sum of the largest indexes, or the sum of (columnlength+rowlength-2).
Therefore, my solution is to iterate through the diagonal row numbers and print all index pairs whose sum is equal to the current diagonal row.
var TheArray = ["ABCD","EFGH","IJKL"];
//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;
var text = ''
for (i = 0; i <= (RowLength+ColumnLength-2); i++){
for (x = 0; x<=i; x++){
if (TheArray[i-x] && TheArray[i-x][x]){
text += TheArray[i-x][x];
}
}
text += "<br/>";
}
document.getElementById('text').innerHTML = text;
JSFiddle Link
Here is my try for 'from top left to bottom right':
for (i=0; i<nbRows; i++) {
x = 0; y = i;
while (x < nbColumns && y >= 0) {
print(array[x, y]);
x++; y--;
}
print("\n");
}
for (i=1; i<nbColumns; i++) {
x = i; y = nbRows - 1;
while (x < nbColumns && y >=0) {
print(array[x, y]);
x++; y--;
}
}
Needs a few adaptations to fit JavaScript syntax.
Full solution for both diagonals:
var TheArray = ['ABCD', 'EFGH', 'IJKL'];
var RowLength = TheArray.length;
var ColumnLength = TheArray[0].length;
// Diagonals
var diagonal = [[], []];
for (var i = 0; i < Math.min(RowLength, ColumnLength); i++) {
diagonal[0].push({'row': 0-i, 'col': i});
diagonal[1].push({'row': 0-i, 'col': 0-i});
}
// Entry points
// 1///
// 2///
// 3456
var points = [[], []];
for (var y = 0; y < RowLength; y++) {
points[0].push({'row': y, 'col': 0});
}
for (var x = 1; x < ColumnLength; x++) {
points[0].push({'row': RowLength - 1, 'col': x});
}
// Entry points
// \\\6
// \\\5
// 1234
for (var x = 0; x < ColumnLength; x++) {
points[1].push({'row': RowLength - 1, 'col': x});
}
for (var y = RowLength - 2; y >= 0; y--) {
points[1].push({'row': y, 'col': ColumnLength - 1});
}
var strings = [[], []];
for (var line = 0; line < diagonal.length; line++) {
for (var point = 0; point < points[line].length; point++) {
var inside = true;
var index = 0;
var string = '';
while (inside && index < diagonal[line].length) {
var row = points[line][point]['row'] + diagonal[line][index]['row'];
var col = points[line][point]['col'] + diagonal[line][index]['col'];
if (row >= 0 && row < RowLength && col >= 0 && col < ColumnLength) {
string += TheArray[row][col];
index++;
} else {
inside = false;
}
}
strings[line].push(string);
}
}
console.log(strings);
I am continuing to animate a model of a transportation system. The code builds stations, connects them with lines, builds "pods" to run along them, then works out the shortest path between random start and end stations.
jsfiddle
The problems I am having are
a) the pods are traveling one at a time, rather than simultaneously.
b) the pod color is supposed to be related to the number of passengers, but this is clearly not happening.
c) I suspect I am producing a bottleneck in calculating the animation points, as it seems to run more hesitantly than it should.
I would also like to be able to flag the arrival of each pod, so that it can be reloaded, and start a new journey.
Something is wrong with the animation section, but I can't work out what. Any help would be appreciated!
animate();
var lastTime = 0;
var speed = 1; // higher is slower
function animate(time) {
for (var i = 0; i < podArray.length; i++) {
var aPod = podArray[i];
// calculate incremental points along the path
var points = calcWaypoints(aPod.wayStations);
// return if the desired time hasn't elapsed
if ((time - lastTime) < speed) {
requestAnimationFrame(animate);
return;
}
lastTime = time;
//function animate(){
ctx3.clearRect(0, 0, layer3.width, layer3.height);
if (t < points.length - 1) {
requestAnimationFrame(animate);
}
// draw pod from the last waypoint to the current waypoint
ctx3.beginPath();
ctx3.moveTo(aPod.startX, aPod.startY); //(points[t - 1].x, points[t - 1].y);
ctx3.arc(points[t].x, points[t].y, 4, 0, Math.PI * 2, true);
ctx3.fillStyle = aPod.color;
ctx3.fill();
t++;
}
}
a) Your calcWaypoints function takes a parameter that is a list of waystation, and then you ignore that parameter and calculate all points for all pods. This is creating one big array of all points, starting with the first pod's points, then the 2nd's, etc. This is why it starts with the first, then the 2nd then the third.
function calcWaypoints(nextArray) {
var frams = 100;
var waypoints = [];
for (var i = 1; i < nextArray.length; i++) {
var pt0 = nextArray[i - 1];
var pt1 = nextArray[i];
var dx = pt1[0] - pt0[0];
var dy = pt1[1] - pt0[1];
for (var j = 0; j < frams; j++) {
var x = pt0[0] + dx * j / frams //+ dxOff;
var y = pt0[1] + dy * j / frams //+ dyOff;
waypoints.push({
x: x,
y: y
});
};
}
return waypoints;
}
b) This has the same cause as the previous, because you are using the same points for each pod, the pods are written over one another. In addition, you are clearing the canvas between each point. This clear should be moved out of the loop. ctx3.clearRect(0, 0, layer3.width, layer3.height);
c) For some reason you are re-calculating all points with every call to animate. You should calculate them all upfront once and then not in animate. You are also creating way too many calls to requestAnimationFrame in your loop.
I hacked together a few of the above changes and it is working. You should still clean it up a lot more:
layer1 = document.getElementById('layer1');
ctx1 = layer1.getContext('2d');
layer2 = document.getElementById('layer2');
ctx2 = layer2.getContext('2d');
layer3 = document.getElementById('layer3');
ctx3 = layer3.getContext('2d');
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
//STATIONS*************************************
var station = [
['A', 150, 100],
['B', 300, 100],
['C', 200, 175],
['D', 100, 250],
['E', 300, 250],
['G', 400, 250],
['F', 350, 200],
['Airport', 500, 200],
['Central', 500, 350]
];
function draw2() {
for (var i = 0; i < station.length; i++) {
var radius = 10;
ctx2.beginPath();
ctx2.arc(station[i][1], station[i][2], radius, 0, 2 * Math.PI);
ctx2.stroke();
ctx2.fillStyle = 'yellow';
ctx2.fill();
//ADD STATION LETTERS
ctx2.font = '10pt Calibri';
ctx2.fillStyle = 'black';
ctx2.textAlign = 'center';
ctx2.fillText(station[i][0], station[i][1], (station[i][2]) + 4);
}
}
draw2();
//END STATIONS*************************************
//START LINES**************************************
var lineArray = [
['A', 'B', ],
['B', 'A', 'C'],
['C', 'B', 'D', 'E'],
['D', 'C', 'E'],
['E', 'D', 'F', 'G', 'Central'],
['F', 'E', 'G'],
['G', 'F', 'E', 'Airport'],
['Airport', 'G', 'Central'],
['Central', 'E', 'Airport']
];
function drawLines() {
for (m = 0; m < lineArray.length; m++) {
ctx1.lineWidth = 1;
ctx1.beginPath();
for (p = 1; p < lineArray[m].length; p++) {
var startStat = lineArray[m][0];
var stat = lookUp(startStat);
var beginX = station[stat][1];
var beginY = station[stat][2];
ctx1.moveTo(beginX, beginY);
var endStat = lineArray[m][p];
var endSt = lookUp(endStat);
var closeX = station[endSt][1];
var closeY = station[endSt][2];
ctx1.lineTo(closeX, closeY);
}
ctx1.stroke();
}
}
drawLines();
//END LINES*************************************
//SHORTEST PATH*********************************
function Graph() {
var neighbors = this.neighbors = {}; // Key = vertex, value = array of neighbors.
this.addEdge = function (u, v) {
if (neighbors[u] === undefined) { // Add the edge u -> v.
neighbors[u] = [];
}
neighbors[u].push(v);
if (neighbors[v] === undefined) { // Also add the edge v -> u in order
neighbors[v] = []; // to implement an undirected graph.
} // For a directed graph, delete
neighbors[v].push(u); // these four lines.
};
return this;
}
function shortestPath(graph, source, target) {
var stationPath = [];
var coordPath = [];
if (source == target) { // Delete these four lines if
print(source); // you want to look for a cycle
return; // when the source is equal to
} // the target.
var queue = [source],
visited = {
source: true
},
predecessor = {},
tail = 0;
while (tail < queue.length) {
var u = queue[tail++], // Pop a vertex off the queue.
neighbors = graph.neighbors[u];
for (var i = 0; i < neighbors.length; ++i) {
var v = neighbors[i];
if (visited[v]) {
continue;
}
visited[v] = true;
if (v === target) { // Check if the path is complete.
var path = [v]; // If so, backtrack through the path.
while (u !== source) {
path.push(u);
u = predecessor[u];
}
path.push(u);
path.reverse();
print(path.join(' → '));
//console.log('Path: ' + path);
for (s = 1; s < path.length; s++) {
stationPath.push(path[s]);
}
//console.log('Waypoints: ' + stationPath);
for (t = 0; t < stationPath.length; t++) {
staCo = lookUp(stationPath[t]);
staCoX = station[staCo][1];
staCoY = station[staCo][2];
coordPath.push([staCoX, staCoY]);
}
//console.log(coordPath);
return coordPath;
}
predecessor[v] = u;
queue.push(v);
}
}
print('there is no path from ' + source + ' to ' + target);
}
function print(s) { // A quick and dirty way to display output.
s = s || '';
document.getElementById('display').innerHTML += s + '<br>';
}
function findShortestPath(s1, s2) {
var graph = new Graph();
for (w = 0; w < lineArray.length; w++) {
var baseStation = lineArray[w][0];
for (z = 1; z < lineArray[w].length; z++) {
graph.addEdge(baseStation, lineArray[w][z]);
}
}
return (shortestPath(graph, s1, s2));
};
function lookUp(sta) {
//console.log(sta);
for (n = 0; n < station.length; n++) {
if (sta == station[n][0]) {
return n;
break;
}
}
}
//BUILD PODS*************************************
var podArray = [];
function Pod(startX, startY, wayStations, riders, color) {
this.startX = startX;
this.startY = startY;
this.wayStations = wayStations;
this.riders = riders;
this.color = color;
}
var colorArray = ['gold', 'orange', 'red', 'green', 'blue', 'black'];
function randomPass() {
occ = 1 + Math.floor(Math.random() * 6);
return occ;
}
//PROGRAM PODS*********************************************
for (i = 0; i < 3; i++) { //NUMBER OF PODS
//Start Station
var startOff = Math.floor(Math.random() * station.length);
var begSta = station[startOff][0];
var fromX = station[startOff][1];
var fromY = station[startOff][2];
//END STATION
var destNum = Math.floor(Math.random() * station.length);
while (startOff == destNum) {
destNum = Math.floor(Math.random() * station.length);
}
var endSta = station[destNum][0];
function getWayStations(beg, end) {
var fsp = findShortestPath(beg, end);
var nextArray = [];
nextArray.push([fromX, fromY]);
for (var f = 0; f < fsp.length; f++) {
nextArray.push(fsp[f]);
}
return nextArray;
}
//LOAD POD DATA
podArray.push(new Pod(
startX = fromX,
startY = fromY,
wayStations = getWayStations(begSta, endSta),
riders = randomPass(),
color = colorArray[riders - 1]))
}
//END PROGRAM PODS*********************************************
// calc waypoints traveling along nextArray
function calcWaypoints(nextArray) {
var frams = 100;
var waypoints = [];
for (var i = 1; i < nextArray.length; i++) {
var pt0 = nextArray[i - 1];
var pt1 = nextArray[i];
var dx = pt1[0] - pt0[0];
var dy = pt1[1] - pt0[1];
for (var j = 0; j < frams; j++) {
var x = pt0[0] + dx * j / frams //+ dxOff;
var y = pt0[1] + dy * j / frams //+ dyOff;
waypoints.push({
x: x,
y: y
});
};
}
return (waypoints);
}
animate();
var lastTime = 0;
var speed = 1; // higher is slower
function animate(time) {
// return if the desired time hasn't elapsed
if ((time - lastTime) < speed) {
requestAnimationFrame(animate);
return;
}
lastTime = time;
ctx3.clearRect(0, 0, layer3.width, layer3.height);
var callAgain = false;
for (var i = 0; i < podArray.length; i++) {
var aPod = podArray[i];
// calculate incremental points along the path
var points = calcWaypoints(aPod.wayStations);
if (t < points.length - 1) {
callAgain = true;
}
// draw pod from the last waypoint to the current waypoint
if(points.length > t){
ctx3.beginPath();
ctx3.moveTo(aPod.startX, aPod.startY); //(points[t - 1].x, points[t - 1].y);
ctx3.fillStyle = aPod.color;
ctx3.arc(points[t].x, points[t].y, 4, 0, Math.PI * 2, true);
ctx3.fill();
}
}
t++;
if(callAgain) requestAnimationFrame(animate);
}
<canvas id='layer1' style='z-index: 2;
position:absolute;
left:0px;
top:0px;
' height='600px' width='1000'>This text is displayed if your browser does not support HTML5 Canvas.</canvas>
<canvas id='layer2' style='z-index: 3;
position:absolute;
left:0px;
top:0px;
' height='600px' width='1000'>This text is displayed if your browser does not support HTML5 Canvas.</canvas>
<canvas id='layer3' style='z-index: 1;
position:absolute;
left:0px;
top:0px;
' height='600px' width='1000'>This text is displayed if your browser does not support HTML5 Canvas.</canvas>
<div id="display">
</id>