What is the most efficient way to arrange images radially using javascript? - javascript

I have been racking my brain on how to make this work. I can find no examples of this and actually no previous questions. Basically I have a 121 thumbnail images (with the exact same dimensions), arrange them in a grid with gutters and I want to take the first image and place it in the center. (this allows for an 11x11 image grid) Then I would like to take each next image and begin to arrange them around the center image using the next closest available vacant location to the center image until all used up. It is assumed the list of images will be gotten from an array object. What is the most efficient way of doing this?

Most likely not the most efficient way of solving this, but I wanted to play with it:
You could iterate over all the points in your grid, calculate their distances to the center point and then sort the points by this distance. The advantage over the algorithmic solutions is that you can use all sorts of distance functions:
// Setup constants
var arraySize = 11;
var centerPoint = {x:5, y:5};
// Calculate the Euclidean Distance between two points
function distance(point1, point2) {
return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2));
}
// Create array containing points with distance values
var pointsWithDistances = [];
for (var i=0; i<arraySize; i++) {
for (var j=0; j<arraySize; j++) {
var point = {x:i, y:j};
point.distance = distance(centerPoint, point);
pointsWithDistances.push(point);
}
}
// Sort points by distance value
pointsWithDistances.sort(function(point1, point2) {
return point1.distance == point2.distance ? 0 : point1.distance < point2.distance ? -1 : 1;
});
The resulting pointsWithDistances array will look like this:
[
{x:5, y:5, distance:0},
{x:4, y:5, distance:1},
{x:5, y:4, distance:1},
...
{x:4, y:4, distance:1.4142135623730951},
{x:4, y:6, distance:1.4142135623730951},
...
{x:3, y:5, distance:2},
...
]
By iterating over the array in this order you are effectively filling the grid from the center outwards.
(Thanks for Andreas Carlbom's idea how to display this structure.)
Check out the difference to using Rectilinear Distances:
// Rectilinear Distance between two points
function distance(point1, point2) {
return Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y);
}
For the shell-like structure of the algorithmic approaches you can use the Maximum Metric:
// 'Maximum Metric' Distance between two points
function distance(point1, point2) {
return Math.max(Math.abs(point1.x - point2.x), Math.abs(point1.y - point2.y));
}
You can play with the code here: http://jsfiddle.net/green/B3cF8/

Related

What format polygon does D3plus largest rectangle require?

I found an interesting demo of how to find the largest rectangle in an irregular shaped polygon here using D3plus.
I'm trying to recreate this for a polygon I'm working on but currently the code is not working. It seems to runs endlessly. The code I'm using is as follows:
d3.csv("data/polyPoints.csv", function(error, polyPoints) {
if (error) return console.error(error);
// coerce string values to numbers
polyPoints.forEach(function(d) {
d3.keys(d).forEach(function(k) {
d[k] = +d[k]
})
});
// settings for geom.largestRect
var rectOptions = {
angle: 0,
maxAspectRatio: 5,
nTries: 1
};
console.log(rectOptions);
console.log(polyPoints);
var lRect = d3plus.geom.largestRect(polyPoints, rectOptions);
console.log(lRect);
});
I suspect my polygon is not in the correct format.
Update
I'm making progress. My original polygon object was taken from a csv and created an array of arrays of key value pairs (e.g. {"x": 0 "y": 1},{"x": 2, "y": 1}....)
I converted this to an array of arrays (e.g. [[1,0],[2,0]....])
Now the code is running but the output is defining rectangles that cross the boundary of the original polygon.
For anyone working with this. The largestRect docs are https://d3plus.org/docs/#largestRect and can be run with the following code.
const d3p = require('d3plus');
const polygon = [[x,y],[x,y],[x,y]...]
const rectOptions = {
maxAspectRatio: 5,
nTries: 20
};
let lRect = d3p.largestRect(rdp, rectOptions);
The algorithm used is an approximation and random points inside the polygon are chosen to do calculations from. Because of this the edges of the box won't always be touching the edge but should be "close enough".
The options.tolerance value might affect this as well but I haven't played around with it much. This is a pretty old question but hopefully it helps someone.

Create convex hull with array of points in opencv.js

Im trying to create a convex hull with opencv.js based on an array with points, does anyone know a way to do this correctly and efficient? An array would look like this:
[
[5,5],
[10,10],
[15,15]
...
]
-> where the first value would be the x and the second the y value, but it wouldn't be a problem to change this format to something more suitable.
Thnx for the help :)
As far I could experiment OpenCV stores contour/hull data in Mat format with type CV_32SC2: essentially a flat list of 32bit short integers in [x1,y1,x2,y2,x3,y3,...] order.
Note the two channels/planes part of 32SC2: one channel for all the x values and another for all the y values
You can manually create such a Mat, access it's data32S property and fill in each value:
let testHull = cv.Mat.ones(4, 1, cv.CV_32SC2);
testHull.data32S[0] = 100;
testHull.data32S[1] = 100;
testHull.data32S[2] = 200;
testHull.data32S[3] = 100;
testHull.data32S[4] = 200;
testHull.data32S[5] = 200;
testHull.data32S[6] = 100;
testHull.data32S[7] = 200;
However OpenCV.js comes with a handy method to convert a flat array of values to such a Mat:
let testHull = cv.matFromArray(4, 1, cv.CV_32SC2, [100,100,200,100,200,200,100,200])
If your array is nested, you can simply use JS Array's flat() method to flatten it from a 2D array([[x1,y1]...]) to a 1D array ([x1,y1,...]).
So you don't have to worry about the Mat type and all that you can wrap it all into a nice function, for example:
function nestedPointsArrayToMat(points){
return cv.matFromArray(points.length, 1, cv.CV_32SC2, points.flat());
}
Here's a quick demo:
function onOpenCvReady(){
cv.then(test);
}
function nestedPointsArrayToMat(points){
return cv.matFromArray(points.length, 1, cv.CV_32SC2, points.flat());
}
function test(cv){
console.log("cv loaded");
// make a Mat to draw into
let mainMat = cv.Mat.zeros(30, 30, cv.CV_8UC3);
// make a fake hull
let points = [
[ 5, 5],
[25, 5],
[25,25],
[ 5,25]
]
let hull = nestedPointsArrayToMat(points);
console.log("hull data", hull.data32S);
// make a fake hulls vector
let hulls = new cv.MatVector();
// add the recently created hull
hulls.push_back(hull);
// test drawing it
cv.drawContours(mainMat, hulls, 0, [192,64,0,0], -1, 8);
// output to canvas
cv.imshow('canvasOutput', mainMat);
}
<script async src="https://docs.opencv.org/4.4.0/opencv.js" onload="onOpenCvReady();" type="text/javascript"></script>
<canvas id="canvasOutput" width="30" height="30"></canvas>
Note that the above is a rough example, there's no data validation or any other fancier checks, but hopefully it illustrates the idea so it can be extended robustly as required.
Lets say that your points represent a contour:
var contours = new cv.MatVector();
for (var i = 0; i < points.size(); ++i) {
contours.push_back(new cv.Mat(points[i][0], points[i][1])
}
Now following this tutorial from opencv website:
// approximates each contour to convex hull
for (var i = 0; i < contours.size(); ++i) {
var tmp = new cv.Mat();
var cnt = contours.get(i);
// You can try more different parameters
cv.convexHull(cnt, tmp, false, true);
hull.push_back(tmp);
cnt.delete(); tmp.delete();
}

how to align fabric objects with rotation?

I my fabric application, I want to align the selected objects, for example, to the left. Because objects might be rotated (and or scaled), thus, aligning objects actually mean align the bounding boxes of the objects to some edge.
For non-rotated objects, that's quite trivial to implement.
See sample code below:
// find the minimum 'left' value
// function 'min' is used to find the minimum value of a
// given array of objects by comparing the property value
// which is returned by a given callback function
const { minValue } = min(objects, object => {
const left = object.get('left');
const originX = object.get('originX');
if (originX === 'center') {
return left - (object.get('width') * object.get('scaleX')) / 2;
}
return left;
});
objects.forEach(object => {
if (object.get('originX') === 'center') {
object.set('left', minValue + (
object.get('width') * object.get('scaleX')
) / 2);
} else {
object.set('left', minValue);
}
});
canvas.renderAll();
However, it's quite complicated for rotated objects. I have to translate the rotated objects either horizontally or vertically to some calculated offset/distance.
Can anybody give some advise on this? thanks.
After a small research, I found this demo on the official fabricjs website.
Basically you can do:
var bound = obj.getBoundingRect();
Then use bound.top, bound.left, bound.width, bound.height as the bounding rectangle coordinates.

Need a solid way to set relational indices for object polygons drawn in a canvas element

Okay this is going to be hard to explain. So bear with me.
Im having less of a problem with the programming, and more a problem with the idea behind what Im trying to do.
I have a grid of triangles. Ref: http://i.imgur.com/08BPHiD.png [1]
Each triangle is it's own polygon on a canvas element that I have set as an object within the code. The only difference between the objects is the coordinates that I pass through as parameters of a function like so:
var triCoordX = [1, 2, 3, ...];
var triCoordY = [1, 2, 3, ...];
var triCoordFlipX = [1, 2, 3, ...];
var triCoordFlipY = [1, 2, 3, ...];
var createTri = function(x, y, z) {
return {
x: x,
y: y,
sides: 3,
radius: 15,
rotation: z,
fillRed: 17,
fillGreen: 17,
fillBlue: 17,
closed: true,
shadowColor: '#5febff',
shadowBlur: 5,
shadowOpacity: 0.18
}
};
for (i = 0; i < triCoordX.length; i++){
var tri = new Kinetic.RegularPolygon(createTri(triCoordX[i], triCoordY[i], 0));
}
for (i = 0; i < triCoordFlipX.length; i++){
var triFlip = new Kinetic.RegularPolygon(createTri(triCoordFlipX[i], triCoordFlipY[i], 180));
}
Now what Im trying to do exactly is have each object polygon be able to 'recognise' its neighbors for various graphical effects.
How I propose to do this is pass a 4th parameter into the function that I push from another array using the for loop that sets a kind of "index" for each polygon. Also in the for loop I will define a function that points to the index 'neighbors' of the object polygon.
So for instance, if I want to select a random triangle from the grid and make it glow, and on completion of a tween want to make one of it's neighbors glow I will have the original triangle use it's object function to identify a 'neighbor' index and pick at random one of its 3 'neighbors'.
The problem is with this model, Im not entirely sure how to do it without large amounts of bloat in my programming, or when I set the function for the loop, to set a way for the loop to intuitively pick the correct index numbers for what are actually the triangle's neighbors.
If all of that made sense, Im looking for any and all suggestions.
Think of your triangles as being laid out in a grid with the triangle in the top left corner being col==0, row==0.
Then you can find the row/col coordinates of the 3 neighbors of any triangle with the following function.
Ignore any neighbors with the following coordinates because the neighbors would be off the grid.
col<0
row<0
col>ColumnCount-1
row>RowCount-1
Example code (warning...untested code--you may have to tweak it):
function findNeighbors(t){
// determine if this triangle's row/col are even or odd
var evenRow=(t.col%2==0);
var evenCol=(t.row%2==0;
// left neighbor is always the same
n1={ col:t.col-1, row:t.row };
// right neighbor is always the same
n2={ col:t.col+1, row:t.row };
// third neighbor depends on row/col being even or odd
if(evenRow && evenCol){
n3={ col:t.col, row:t.row+1 };
}
if(evenRow && !evenCol){
n3={ col:t.col, row:t.row-1 };
}
if(!evenRow && evenCol){
n3={ col:t.col, row:t.row-1 };
}
if(!evenRow && !evenCol){
n3={ col:t.col, row:t.row+1 };
}
// return an array with the 3 neighbors
return([n1,n2,n3]);
}

Always load startpoint (DIV-position) from given coordinates

I am trying to create a game where you have to move a ball on a platform. At the start of the game, the ball is dropped on the platform and then you can move it around with the arrow keys. This is al working, no problems here.
The game starts with a ball dropped on a yellow tile as can be seen in my fiddle (click the 1 to start). The platform is build in javascript as follows (for level 1 and 2):
var levels = [
[
[1,1,1,1,1],
[1,1,1,1,1],
[1,2,1,1,1]
],
[
[1,1,1,2,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
];
Where 1 = green tile, 0 = no tile and 2 is a yellow tile.
To let the ball drop on the yellow tile, I have the following code:
go: function() {
ball.reset((1*100+50),(2*100+50));
start();
}
Where (1*100+50) is the x-coordinate of the yellow tile and (2*100+50) the y. Better explained: 1 is 1 tile to the right * tile length + 50 ( +50 is to drop the ball in the middle of the div). All works as intended.
But if I load level 2 (see the fiddle, click the 2), we see that the yellow tile is moved, but the ball is still dropped at the fixed spot (see go: function). This is what I need to fix.
I want these yellow tile coordinates to be loaded when a level is loaded. In this case, the simplest thing to do is to add these coordinates with each level. I thought about something like this:
var levels = [
{
yellowTile : [1, 2],
tiles : [ [1,1,1,1,1],
[1,1,1,1,1],
[1,2,1,1,1] ]
},
{
yellowTile : [3, 0],
tiles : [ [1,1,1,2,1],
[1,1,1,1,1],
[1,1,1,1,1] ]
}
];
So the go: function will be like:
go: function() {
ball.reset((yellowTileX*100+50),(yellowTileY*100+50));
start();
}
But I have no luck in making this work. Hope someone can help me out here.
Many thanks
The easiest way to find the start position is to save it when looping all the tiles. I've modified your script so the start position is saved by adding the following to loadLevel:
if(levels[level][i][j] === 2) {
startPosition = {x: j, y: i};
}
I've added the function getStartPosition() to the plane class, this function can be used in the 'go' function to fetch the start x and y of the plane. This can be used to reset the ball to the correct x and y
go: function() {
ball.reset((plane.getStartPosition().x*100+50),(plane.getStartPosition().y*100+50));
start();
}
Check out my modified version: http://jsfiddle.net/BKEbL/7/

Categories