以下代码生成随机点(x,y),然后针对每个点将画布(一个正方形)分成四个。对于迭代中的下一个点,它将搜索该点所在的正方形,并将其分成四个较小的正方形-达到一定的正方形大小。
问题在于,在Chrome中运行速度非常快,而在Ps中运行速度非常慢(在Chrome中1k点需要2秒,在Ps中需要30分钟!在1k点中Ps需要大约10秒。
是否有更好的重写方法?顺便说一句,PS不支持ES5
var squares = [];
var canvaswidth = app.activeDocument.width.as("px");
var canvasheight = app.activeDocument.height.as("px");
squares.push([{
x: 0,
y: 0
}, {
x: canvaswidth,
y: 0
}, {
x: canvaswidth,
y: canvasheight
}, {
x: 0,
y: canvasheight
}])
vertices = [];
for (i = 0; i < 8000; i++) {
vertices.push({
x: Math.floor(Math.random() * canvaswidth),
y: Math.floor(Math.random() * canvasheight)
})
}
var t0 = new Date().getTime();
var minsquaresize = 24;
for (v = 0; v < vertices.length; v++) {
if (v > 0 && Math.abs(vertices[v].x - vertices[v - 1].x) > minsquaresize && Math.abs(vertices[v].y - vertices[v - 1].y) > minsquaresize) {
r = 2;
for (s = 0; s < squares.length; s++) {
var squares_s = squares[s];
if (squares_s != undefined && vertices[v].x >= squares_s[0].x && vertices[v].x <= squares_s[2].x && vertices[v].y >= squares_s[0].y && vertices[v].y <= squares_s[2].y && squares_s[1].x - squares_s[0].x > minsquaresize && squares_s[3].y - squares_s[0].y > minsquaresize) {
var s1p1 = {
x: Math.round(squares_s[0].x),
y: Math.round(squares_s[0].y)
};
var s1p2 = {
x: Math.round((squares_s[0].x + squares_s[1].x) / 2),
y: Math.round((squares_s[0].y + squares_s[1].y) / 2)
};
var s1p3 = {
x: Math.round(((squares_s[1].x - squares_s[0].x) / r) + squares_s[0].x),
y: Math.round(((squares_s[3].y - squares_s[0].y) / r) + squares_s[0].y)
}
var s1p4 = {
x: (squares_s[0].x + squares_s[3].x) / 2,
y: Math.round((squares_s[0].y + squares_s[3].y) / 2)
}
var s2p2 = {
x: squares_s[1].x,
y: squares_s[1].y
}
var s2p3 = {
x: Math.round((squares_s[1].x + squares_s[2].x) / 2),
y: Math.round((squares_s[1].y + squares_s[2].y) / 2)
}
var s3p3 = {
x: squares_s[2].x,
y: squares_s[2].y
}
var s3p4 = {
x: Math.round((squares_s[2].x + squares_s[3].x) / 2),
y: Math.round(Math.round((squares_s[2].y + squares_s[3].y) / 2))
}
var s4p4 = {
x: squares_s[3].x,
y: squares_s[3].y
}
//alert(s4p4.y)
delete squares[s];
squares.push([s1p1, s1p2, s1p3, s1p4])
squares.push([s1p2, s2p2, s2p3, s1p3])
squares.push([s1p3, s2p3, s3p3, s3p4])
squares.push([s1p4, s1p3, s3p4, s4p4])
break;
}
}
}
}
var t1 = new Date().getTime() - t0;
alert("time: "+t1)
答案 0 :(得分:0)
通过使方块反向循环,可以显着提高性能。 所以通常是:
for(vertices length, v++){
for(squares length, s++){
if vertex is within square then delete square from square array, split square into 4 equal squares and add them to array
}
}
顶点是从路径中收集的,因此顶点4可能会接近顶点3,因此可能在从顶点3创建的最后一个正方形的区域中-在正方形数组的末尾。所以:
for(var s = squares.length; s--;){...}
这工作得快得多(也许10倍)。奇怪的是,对于随机放置的顶点来说,速度也更快。