主要是一些小细节。
基于JS的蒙德里安风格随机色块生成(1)
基于JS的蒙德里安风格随机色块生成(2)
目前我们已经获得了所有交点。要想通过这些交点生成矩形,我们按照以下思路实现。显然,三个交点就能确定唯一的矩形。选取一个交点,作为矩形左上角的顶点。判断该点类型是否为U或L或UL,然后判断该点右侧是否存在类型为U或R或UR的点,再判断下方是否存在类型为D或L或DL的点。后两步都要选取最近的点,如果不存在就回溯遍历,遍历所有点为左上点。
深拷贝
这要求分别按照两个特征坐标(沿用直线概念,见上节)对交点排序。在这个过程中,我忽视了浅拷贝和深拷贝的区别,深深的怀疑了javascript。这里直接借鉴了别人的写法。https://www.cnblogs.com/matthew-2013/p/3524297.html 作者:matthew2015
//感谢https://www.cnblogs.com/matthew-2013/p/3524297.html 作者:matthew2015
function deepcopy(obj) {
var out = [], i = 0, len = obj.length;
for (; i < len; i++) {
if (obj[i] instanceof Array) {
out[i] = deepcopy(obj[i]);
}
else out[i] = obj[i];
}
return out;
}
按特征坐标排序
数组的sort
方法接受以匿名函数作为参数,该匿名函数接受sort隐性的临时变量a
和b
,返回一个判断依据。默认是差值小于零则a
在b
之前(可以调控a-b
还是b-a
来实现升序或降序),反之亦然。sort
方法是对整个数组排序,a
和b
是隐性的不断改变的。
function sortByColumn(arr) {
arr.sort(function (a, b) {
return a[0] - b[0];
});
return arr;
}
function sortByRow(arr) {
arr.sort(function (a, b) {
return a[1] - b[1];
});
return arr;
}
最近点查找
function findClosestColumn(arr, coord) {
let closestColumn = Infinity;
let closestPoint = null;
for (let i = 0; i < arr.length; i++) {
if (arr[i][1] == coord[1]) {
let diffColumn = arr[i][0] - coord[0];
if (diffColumn > 0 &&
diffColumn < closestColumn) {
if (arr[i][2] == 'U' ||
arr[i][2] == 'R' ||
arr[i][2] == 'UR') {
closestColumn = diffColumn;
closestPoint = arr[i];
}
}
}
}
return closestPoint;
}
function findClosestRow(arr, coord) {
let closestRow = Infinity;
let closestPoint = null;
for (let i = 0; i < arr.length; i++) {
if (arr[i][0] == coord[0]) {
let diffRow = arr[i][1] - coord[1];
if (diffRow > 0 &&
diffRow < closestRow) {
if (arr[i][2] == 'D' ||
arr[i][2] == 'L' ||
arr[i][2] == 'DL') {
closestRow = diffRow;
closestPoint = arr[i];
}
}
}
}
return closestPoint;
}
矩形数据生成
矩形参数包括:左上基准点、长、宽、序号
let intersectionByColumn = deepcopy(intersectionInfo);
let intersectionByRow = deepcopy(intersectionInfo);
intersectionByColumn = sortByColumn(sortByRow(intersectionByColumn));
intersectionByRow = sortByRow(sortByColumn(intersectionByRow));
var blockInfo = [];
var blockNum = 0;
let tmpVariableA = [];
let tmpVariableB = [];
for (let i = 0; i < intersectionInfo.length; i++) {
if (intersectionByRow[i][2] == 'U' ||
intersectionByRow[i][2] == 'L' ||
intersectionByRow[i][2] == 'UL') {
tmpVariableA = findClosestColumn(intersectionByRow, intersectionByRow[i]);
if ((tmpVariableA != null) &&
(tmpVariableA[2] == 'U' ||
tmpVariableA[2] == 'R' ||
tmpVariableA[2] == 'UR')) {
tmpVariableB = findClosestRow(intersectionByColumn, intersectionByRow[i]);
if ((tmpVariableB != null) &&
(tmpVariableB[2] == 'D' ||
tmpVariableB[2] == 'L' ||
tmpVariableB[2] == 'DL')) {
blockInfo[blockNum] = [intersectionByRow[i], (tmpVariableA[0] - intersectionByRow[i][0]), (tmpVariableB[1] - intersectionByRow[i][1]), blockNum];
blockNum++;
}
}
}
}
评论区(暂无评论)