В Python:
def do_polygons_intersect(a, b):
"""
* Helper function to determine whether there is an intersection between the two polygons described
* by the lists of vertices. Uses the Separating Axis Theorem
*
* @param a an ndarray of connected points [[x_1, y_1], [x_2, y_2],...] that form a closed polygon
* @param b an ndarray of connected points [[x_1, y_1], [x_2, y_2],...] that form a closed polygon
* @return true if there is any intersection between the 2 polygons, false otherwise
"""
polygons = [a, b];
minA, maxA, projected, i, i1, j, minB, maxB = None, None, None, None, None, None, None, None
for i in range(len(polygons)):
# for each polygon, look at each edge of the polygon, and determine if it separates
# the two shapes
polygon = polygons[i];
for i1 in range(len(polygon)):
# grab 2 vertices to create an edge
i2 = (i1 + 1) % len(polygon);
p1 = polygon[i1];
p2 = polygon[i2];
# find the line perpendicular to this edge
normal = { 'x': p2[1] - p1[1], 'y': p1[0] - p2[0] };
minA, maxA = None, None
# for each vertex in the first shape, project it onto the line perpendicular to the edge
# and keep track of the min and max of these values
for j in range(len(a)):
projected = normal['x'] * a[j][0] + normal['y'] * a[j][1];
if (minA is None) or (projected < minA):
minA = projected
if (maxA is None) or (projected > maxA):
maxA = projected
# for each vertex in the second shape, project it onto the line perpendicular to the edge
# and keep track of the min and max of these values
minB, maxB = None, None
for j in range(len(b)):
projected = normal['x'] * b[j][0] + normal['y'] * b[j][1]
if (minB is None) or (projected < minB):
minB = projected
if (maxB is None) or (projected > maxB):
maxB = projected
# if there is no overlap between the projects, the edge we are looking at separates the two
# polygons, and we know there is no overlap
if (maxA < minB) or (maxB < minA):
print("polygons don't intersect!")
return False;
return True
Вероятно, вы захотите использовать что-то вроде jQuery, которое упрощает программирование JS.
Что-то вроде:
$(document).ready(function(){
// Your code here
});
Похоже, что вы делаете то, что вам нужно.
Если вы действительно хотите, чтобы этот код запускался при load , а не в состоянии готовности (т.е. вам нужно, чтобы изображения также загружались), то, к сожалению, функция готовности не работает. Я делаю это за тебя. Обычно я делаю что-то вроде этого:
Включить в документ javascript (т.е. всегда вызывается перед запуском onload):
var pageisloaded=0;
window.addEvent('load',function(){
pageisloaded=1;
});
Затем ваш код:
if (pageisloaded) {
DoStuffFunction();
} else {
window.addEvent('load',DoStuffFunction);
}
(Или эквивалент в вашей структуре предпочтений.) Я использую этот код для сделать предварительное кэширование javascript и изображений для будущих страниц. Поскольку материалы, которые я получаю, вообще не используются для этой страницы, я не хочу, чтобы они имели приоритет над быстрой загрузкой изображений.
Может быть лучший способ, но я еще не нашел это.
Библиотека не нужна. jQuery какое-то время использовал этот скрипт, кстати.
http://dean.edwards.name/weblog/2006/06/again/
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;