Here is an code in JavaScript. It calculates position for 2D matrix starting with number 1 in a middle (0, 0)

```13  12  11  10  25
14   3   2   9  24
15   4   1   8  23
16   5   6   7  22
17  18  19  20  21

/**
* Finds coordinates (position) of the number
*
* @param {Number} n - number to find position/coordinates for
* @return {Number[]} - x and y coordinates of the number
*/
function position(n) {
const k = Math.ceil((Math.sqrt(n) - 1) / 2);
let t = 2 * k + 1;
let m = Math.pow(t, 2);

t -= 1;

if (n >= m - t) {
return [k - (m - n), -k];
}

m -= t;

if (n >= m - t) {
return [-k, -k + (m - n)];
}

m -= t;

if (n >= m - t) {
return [-k + (m - n), k];
}

return [k, k - (m - n - t)];
}```

Constant time, readable and nice. Myself from 2012 thanks you extensively!

## algorithm - Find the position nth element of a rectangular tiled spira...

algorithm spiral

Here's my solution in javascript using inverse sum of 8 and edge numbering

Complexity : O(1) no iteration loop

```function spiral(n) {
// given n an index in the squared spiral
// p the sum of point in inner square
// a the position on the current square
// n = p + a

var r = Math.floor((Math.sqrt(n + 1) - 1) / 2) + 1;

// compute radius : inverse arithmetic sum of 8+16+24+...=
var p = (8 * r * (r - 1)) / 2;
// compute total point on radius -1 : arithmetic sum of 8+16+24+...

en = r * 2;
// points by edge

var a = (1 + n - p) % (r * 8);
// compute de position and shift it so the first is (-r,-r) but (-r+1,-r)
// so square can connect

var pos = [0, 0];
switch (Math.floor(a / (r * 2))) {
// find the face : 0 top, 1 right, 2, bottom, 3 left
case 0:
{
pos[0] = a - r;
pos[1] = -r;
}
break;
case 1:
{
pos[0] = r;
pos[1] = (a % en) - r;

}
break;
case 2:
{
pos[0] = r - (a %en);
pos[1] = r;
}
break;
case 3:
{
pos[0] = -r;
pos[1] = r - (a % en);
}
break;
}
console.log("n : ", n, " r : ", r, " p : ", p, " a : ", a, "  -->  ", pos);
return pos;
}```

Good work. Just in time!

## algorithm - Find the position nth element of a rectangular tiled spira...

algorithm spiral

This is the javascript solution based on the answer at Looping in a spiral

```var x = 0,
y = 0,
delta = [0, -1],
// spiral width
width = 6,
// spiral height
height = 6;

for (i = Math.pow(Math.max(width, height), 2); i>0; i--) {
if ((-width/2 < x && x <= width/2)
&& (-height/2 < y && y <= height/2)) {
console.debug('POINT', x, y);
}

if (x === y
|| (x < 0 && x === -y)
|| (x > 0 && x === 1-y)){
// change direction
delta = [-delta[1], delta[0]]
}

x += delta[0];
y += delta[1];
}```

## language agnostic - Algorithm for iterating over an outward spiral on ...

algorithm language-agnostic recursion iteration
```function spiralPoint(dist, sep, step) {
this.x = 0;
this.y = 0;

var r = dist;
var b = sep / (2 * Math.PI);
var phi = r / b;
for(n = 0; n < step-1; ++n) {
phi += dist / r;
r = b * phi;
}
this.x = r * Math.cos(phi);
this.y = r * Math.sin(phi);

this.print = function() {
console.log(this.x + ', ' + this.y);
};
}

new spiralPoint(1,1,10).print();```

## javascript - Finding x,y coordinates of a point on an Archimedean spir...

javascript d3.js coordinates spiral

My final implementation based on the link above.

```function archimedeanSpiral(svg,data,circleMax,padding,steps) {
var arcAxis = [];
var angle = 0;
for(var i=0;i<steps;i++){
angle += Math.asin(1/radius);//sin(angle) = opposite/hypothenuse => used asin to get angle
arcAxis.push({"x":x,"y":y})
}
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("cardinal");

svg.append("path")
.attr("d", lineFunction(arcAxis))
.attr("stroke", "gray")
.attr("stroke-width", 5)
.attr("fill", "none");

var circles = svg.selectAll("circle")
.data(arcAxis)
.enter()
.append("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", 10);

return(arcAxis);
}```

## javascript - Finding x,y coordinates of a point on an Archimedean spir...

javascript d3.js coordinates spiral

## JavaScript spiral matrix [Node.js and Hello World]

JavaScript spiral matrix for lab80

```/*jshint node:true*/
"use strict";

var spiral = function (row, col) {
var i, slots = [],
pointer = { x: 0, y: 0, direction: 'x', increase_val: 1 },
isSlotAvail = function (x, y) {
return !(x >= col || y >= row || x < 0 || y < 0 || slots[y][x]);
},
output = [];

// init slots
for (i = 0; i < row; i++) {
slots[i] = [];
}

for (i = 0; i < row * col; i++) {
slots[pointer.y][pointer.x] = i + 1;
pointer[pointer.direction] += pointer.increase_val;

if (!isSlotAvail(pointer.x, pointer.y)) {
pointer[pointer.direction] -= pointer.increase_val;
if (pointer.direction === 'x') {
pointer.direction = 'y';
} else {
pointer.direction = 'x';
pointer.increase_val = -pointer.increase_val;
}
pointer[pointer.direction] += pointer.increase_val;
}
}

// format output
for (i = 0; i < row; i++) {
output.push(slots[i].join("  "));
}
output = output.join("\n");

return output;
};

console.log(spiral(6, 6));
console.log('---------------');
console.log(spiral(5, 7));```
Node.js Hello World

## spiral array [jQuery and JavaScript]

some HTML5 magic

```/*  jQuery ready function. Specify a function to execute when the DOM is fully loaded.  */

/* This is the function that will get executed after the DOM is fully loaded */
function () {
//var result = [spiral(7,7).join("<br/>"), spiral(5,5).join("<br/>"), sprial(3,10).join("<br/>")].join("<br/>");

var spirals = [[3,10], [7,7], [4,4]];
var result = "";
spirals.forEach(function(rowAndCol){
var r = rowAndCol[0];
var c = rowAndCol[1];
result += "<p>"+r+","+c+"<p>"+spiral(r,c).join("<br/>");
});

\$("#status").html(result);
}
);

function spiral(row, col) {
// get array
var rows = [];

for (var i = 0; i < row; i++) {
var cols = [];
for (var j = 0; j < col; j++) {
cols.push(0);
}
rows.push(cols);
}

// set vars
var n = 0;

var turn = "col";
var rowCount = 0;
var colCount = 0;

var rowHeight = row;
var colWidth = col;

var colN = 0;
var rowN = 0;

var d = 1;

// get increasing numbers with spiral order into the array
while (n < row * col) {
if (turn == "col") {
colCount += d;
colN++;
if (colN == colWidth) {
turn = "row";
rowN = 0;
rowHeight--;
}
} else if (turn == "row") {
rowCount += d;
rowN++;
if (rowN == rowHeight) {
turn = "col";
colN = 0;
d *= -1;
colWidth--;
}
}

n++;

rows[rowCount][colCount - 1] = n;
}

return rows;
}```
jQuery JavaScript

It boils down to basic geometry. If you think of a body orbiting a point in 2D, it's movement can be characterised by a radius (distance from the orbited point), and an angle which is a function of time. If you know the radius and the angle, then you can calculate the body position with the cos and sin function.

By changing the radius over time, you obtain a spiral instead of a simple circle.

Thanks for the enlightenment, I think I can play around with it now.

## Spiral Animation JavaScript - Stack Overflow

javascript animation

Using simple algebra thought in high school you can define two functions: linear and spiral.

```function linear(i){
x = i*15;
y = x;
return {cx:x+offset,cy:y+offset};
}

function spiral(i){
r = 50 - i*5;
x = r*Math.cos(i);
y = r*Math.sin(i);
return {cx:x+offset,cy:y+offset};
}```

This is just a 5 min fiddling, so it might seem cheap. Of course, you can define better algorithms using transform functions.

## javascript - How to curl paths into spiral on hover using Raphael JS -...

javascript animation svg raphael

For those of you wanting this plugin, I've added vertical-spiralling and updated it to version 1.2. You'll find the code both on the original forum post and on github: https://github.com/thugsb/jQuery.Spiral

Let me know about any bugs, suggestions for improvement, or even just if you found it helpful. Thanks!

## jQuery spiral animation - Stack Overflow

jquery animation jquery-animate spiral

My final implementation based on the link above.

```function archimedeanSpiral(svg,data,circleMax,padding,steps) {
var arcAxis = [];
var angle = 0;
for(var i=0;i<steps;i++){
angle += Math.asin(1/radius);//sin(angle) = opposite/hypothenuse => used asin to get angle
arcAxis.push({"x":x,"y":y})
}
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("cardinal");

svg.append("path")
.attr("d", lineFunction(arcAxis))
.attr("stroke", "gray")
.attr("stroke-width", 5)
.attr("fill", "none");

var circles = svg.selectAll("circle")
.data(arcAxis)
.enter()
.append("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", 10);

return(arcAxis);
}```

## javascript - Finding x,y coordinates of a point on an Archimedean spir...

javascript d3.js coordinates spiral

Start simply by drawing a piecewise a spiral.

The spiral radius goes from start angle to end angle and the spiral radius goes from inner circle radius to outer circle radius.

To give you an idea of what I mean, choose a number of pieces (n)

```var n = 20, // The number of lines in the spiral
aStep = (outerAngle - innerAngle)/n,  // the angle change between points
points = [];

// compute the cartesian coordinates (x, y) from polar coordinates (r, a)
function cartesian(r, a) {
return [
r * Math.cos(a),
r * Math.sin(a)
];
}

for (i = 0; i <= n; i += 1) {
points.push(cartesian(innerRadius + (i * rStep), innerAngle + (i * aStep));
}```

I have demonstrated a basic piecewise spiral using polar coordinates:

```drawLine(innerCircleIndex, outerCircleIndex, 1); // This is what you did

drawLine(innerCircleIndex, outerCircleIndex, 100); // 100 lines in the example

drawLine(innerCircleIndex, outerCircleIndex, n); // Choose n to see how it grows```

## Challenging vector maths in JavaScript - Stack Overflow

javascript math vector raphael

Here's a JavaScript (ES6) iterative solution to this problem:

```let spiralMatrix = (x, y, step, count) => {
let distance = 0;
let range = 1;
let direction = 'up';

for ( let i = 0; i < count; i++ ) {
console.log('x: '+x+', y: '+y);
distance++;
switch ( direction ) {
case 'up':
y += step;
if ( distance >= range ) {
direction = 'right';
distance = 0;
}
break;
case 'right':
x += step;
if ( distance >= range ) {
direction = 'bottom';
distance = 0;
range += 1;
}
break;
case 'bottom':
y -= step;
if ( distance >= range ) {
direction = 'left';
distance = 0;
}
break;
case 'left':
x -= step;
if ( distance >= range ) {
direction = 'up';
distance = 0;
range += 1;
}
break;
default:
break;
}
}
}```
`spiralMatrix(0, 0, 1, 100);`

This will create an outward spiral, starting at coordinates (x = 0, y = 0) with step of 1 and a total number of items equals to 100. The implementation always starts the movement in the following order - up, right, bottom, left.

Please, note that this implementation creates square matrices.

## algorithm - Looping in a spiral - Stack Overflow

algorithm matrix loops spiral

Just for fun in Javascript:

```function spiral(x, y) {
var iy = ix = 0
, hr = (x - 1) / 2
, vr = (y - 1) / 2
, tt = x * y
, matrix = []
, step = 1
, dx = 1
, dy = 0;

while(matrix.length < tt) {

if((ix <= hr && ix >= (hr * -1)) && (iy <= vr && (iy >= (vr * -1)))) {
console.log(ix, iy);
matrix.push([ix, iy]);
}

ix += dx;
iy += dy;

// check direction
if(dx !== 0) {
// increase step
if(ix === step && iy === (step * -1)) step++;

// horizontal range reached
if(ix === step || (ix === step * -1)) {
dy = (ix === iy)? (dx * -1) : dx;
dx = 0;
}
} else {
// vertical range reached
if(iy === step || (iy === step * -1)) {
dx = (ix === iy)? (dy * -1) : dy;
dy = 0;
}
}
}

return matrix;
}

var sp = spiral(5, 3);```

## algorithm - Looping in a spiral - Stack Overflow

algorithm matrix loops spiral

Here's a JavaScript (ES6) iterative solution to this problem:

```let spiralMatrix = (x, y, step, count) => {
let distance = 0;
let range = 1;
let direction = 'up';

for ( let i = 0; i < count; i++ ) {
console.log('x: '+x+', y: '+y);
distance++;
switch ( direction ) {
case 'up':
y += step;
if ( distance >= range ) {
direction = 'right';
distance = 0;
}
break;
case 'right':
x += step;
if ( distance >= range ) {
direction = 'bottom';
distance = 0;
range += 1;
}
break;
case 'bottom':
y -= step;
if ( distance >= range ) {
direction = 'left';
distance = 0;
}
break;
case 'left':
x -= step;
if ( distance >= range ) {
direction = 'up';
distance = 0;
range += 1;
}
break;
default:
break;
}
}
}```
`spiralMatrix(0, 0, 1, 100);`

This will create an outward spiral, starting at coordinates (x = 0, y = 0) with step of 1 and a total number of items equals to 100. The implementation always starts the movement in the following order - up, right, bottom, left.

Please, note that this implementation creates square matrices.

## algorithm - Looping in a spiral - Stack Overflow

algorithm matrix loops spiral

Just for fun in Javascript:

```function spiral(x, y) {
var iy = ix = 0
, hr = (x - 1) / 2
, vr = (y - 1) / 2
, tt = x * y
, matrix = []
, step = 1
, dx = 1
, dy = 0;

while(matrix.length < tt) {

if((ix <= hr && ix >= (hr * -1)) && (iy <= vr && (iy >= (vr * -1)))) {
console.log(ix, iy);
matrix.push([ix, iy]);
}

ix += dx;
iy += dy;

// check direction
if(dx !== 0) {
// increase step
if(ix === step && iy === (step * -1)) step++;

// horizontal range reached
if(ix === step || (ix === step * -1)) {
dy = (ix === iy)? (dx * -1) : dx;
dx = 0;
}
} else {
// vertical range reached
if(iy === step || (iy === step * -1)) {
dx = (ix === iy)? (dy * -1) : dy;
dy = 0;
}
}
}

return matrix;
}

var sp = spiral(5, 3);```

## algorithm - Looping in a spiral - Stack Overflow

algorithm matrix loops spiral

## Javascript Spiral Matrix [jQuery]

some HTML5 magic

```/*  jQuery ready function. Specify a function to execute when the DOM is fully loaded.  */

/* This is the function that will get executed after the DOM is fully loaded */
function () {

function newSpiralArray(rows, cols) {
var arr = Array(rows);
var total = rows * cols;
var x = 0;
var y = 0;
var dx = 1;
var dy = 0;
var currentNumber = 0;
var xEdgeChecker = 0;
var yEdgeChecker = 0;

var xEdge = cols - 1;
var yEdge = rows - 1;

while(rows) arr[--rows] = [];

while (currentNumber < total) {
arr[y][x] = currentNumber++; //
if (xEdge == 0) {
dx = 0; dy = 1;
}
x += dx; y += dy;

if (dx !== 0) {
if (++xEdgeChecker === xEdge) {
var temp = dx;
dx = -dy;
dy = temp;
xEdgeChecker = 0;
}
} else if (dy !== 0) {
if (++yEdgeChecker === yEdge) {
if (dy < 0) { x++; y++; xEdge -= 2; yEdge -= 2 }
var temp = dx;
dx = -dy;
dy = temp;
yEdgeChecker = 0;

}
}
}

return arr;

}
if (rows = prompt('insert row number')) {
var insertedRowNumber = rows;
if (columns = prompt('insert column number')) {
var insertedColumnNumber = columns;

arr = newSpiralArray(Number(insertedRowNumber),Number(insertedColumnNumber));
for (y= 0; y < Number(insertedRowNumber); y++) console.log(arr[y].join(" "));
\$("#status").html("The result has been printed in the console.");
};
}

}
);```
jQuery JavaScript

It computes y=f(x) for the diagonal, and y2=f(x) for the antidiagonal, then checks if we're above or below the diagonals when needed.

```var x = 0;
var y = 0;
var dx = 0;
var dy = -1;
var width = 200;
var height = 40;
//var i = width * height;
var counter = 0;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

function diag1(x) {
return x*height/width;
}
function diag2(x) {
return -1/diag(x);
}

setInterval(function(){
//for (i = Math.pow(Math.max(width, height), 2); i>0; i--) {

if ((-width/2 < x && x <= width/2)  && (-height/2 < y && y <= height/2)) {
console.log("[ " + x + " , " +  y + " ]");
ctx.fillStyle = "#FF0000";
ctx.fillRect(width/2 + x, height/2 - y,1,1);
}

if (dx == 0) {
if (dy == 1) {
// moving up
if (y >= diag1(x)) {
// then move left
dy = 0;
dx = -1;
}
}
else {
// moving down
if (y <= diag2(x)) {
// then move right
dy = 0;
dx = 1;
}
}
}
else {
if (dx == 1) {
// moving right
if (y <= diag1(x)) {
// then move up
dy = 1;
dx = 0;
}
}
else {
// moving left
if (y <= diag2(x)) {
// then move down
dy = -1;
dx = 0;
}
}
}

counter += 1;
x += dx;
y += dy;
}, 1);```

Don't understand why you'd crash your computer. It's a long time running sequence, but you can end it whenever you want. In the meantime, I'm having some trouble with the diag2value return you passed on the code above. I didn't got where you were trying to go.

check the code I posted above, where the conditions were simplified and the turns are handled by the x_limit and y_limit variables. I believe it becomes more straight forward. I couldn't get your code working.

I realize now the problem. Your x and y variables are offsets to the center, domains [-width/2, width/2] and [-height/2, height/2]. I was using them as locations in the canvas, domains [0,width] and [0,height].

Yes, I needed to offset the origin of the grid, so I could have it starting in the canvas centre.

## javascript - How to draw rectangle spiral? - Stack Overflow

javascript html html5 canvas

A friend helped me handling a proper solution. I only have a 1 pixel offset to solve where I need to move all the drawing to the left by one pixel.

And the Javascript code below:

```var width = 150;
var height = 50;

var x = -(width - height)/2;
var y = 0;
var dx = 1;
var dy = 0;
var x_limit = (width - height)/2;
var y_limit = 0;
var counter = 0;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

setInterval(function(){
if ((-width/2 < x && x <= width/2)  && (-height/2 < y && y <= height/2)) {
console.log("[ " + x + " , " +  y + " ]");
ctx.fillStyle = "#FF0000";
ctx.fillRect(width/2 + x, height/2 - y,1,1);
}
if( dx > 0 ){//Dir right
if(x > x_limit){
dx = 0;
dy = 1;
}
}
else if( dy > 0 ){ //Dir up
if(y > y_limit){
dx = -1;
dy = 0;
}
}
else if(dx < 0){ //Dir left
if(x < (-1 * x_limit)){
dx = 0;
dy = -1;
}
}
else if(dy < 0) { //Dir down
if(y < (-1 * y_limit)){
dx = 1;
dy = 0;
x_limit += 1;
y_limit += 1;
}
}
counter += 1;
x += dx;
y += dy;
}, 1);```

## javascript - How to draw rectangle spiral? - Stack Overflow

javascript html html5 canvas

You cannot do this based solely on any client side operation, to my knowledge. Your problem stems from the fact that your client side JS variables are only available to the individual who is viewing the page. Multiple page views simply mean multiple, separate, and unrelated instances of those variables. The client hosts the JS, so once they leave your page... the scripts they interacted with (thus the variables) are gone. Unless you save them to a place that you host, such as your webserver (this is where a database or data file could live)

In regards to your question within the comments: You could save the file and then read it on page load, however this will be difficult to maintain if ever required and kind of a messy hack (IMO)....

Of course this is not a solution but hopefully it is a starting point.

## How to draw image pixel by pixel, after confirmation of purchase, on a...

javascript image-processing paypal pixel