Filling an array by distance from center
by Julian
HTML
<div id="container"></div>
CSS
#container {
height: 100%;
width: 100%;
}
div.img {
position: absolute;
}
JavaScript
// Setup constants
var arraySize = 11;
var centerPoint = {x:5, y:5};
// This function calculates the distance between two points
function distance(point1, point2) {
// Euclidean Distance:
return Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2));
// Instead, you could also use the more simple Rectilinear Distance:
// return Math.abs(point1.x - point2.x) + Math.abs(point1.y - point2.y);
// Or the 'Maximum Metric' (Chebyshev) Distance:
// return Math.max(Math.abs(point1.x - point2.x), Math.abs(point1.y - point2.y));
}
// 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
pointsWithDistances.sort(function(point1, point2) {
return point1.distance == point2.distance ? 0 : point1.distance < point2.distance ? -1 : 1;
});
// Create output "graphics"
var tileSize = 100.0/arraySize;
var containerContent = "";
var maxDistance = distance(centerPoint, {x:0, y:0});
for (var l=0; l<pointsWithDistances.length; l++) {
var point = pointsWithDistances[l];
var colorValue = parseInt(point.distance / maxDistance * 255, 10);
containerContent += '<div class="img" style="background-color:rgb('+colorValue +',10,100); left:'+Math.floor(point.x*tileSize)+'%; top:'+Math.floor(point.y*tileSize)+'%; width:'+Math.ceil(tileSize)+'%; height:'+Math.ceil(tileSize)+'%"></div>';
}
document.getElementById('container').innerHTML = containerContent;