Почему спавнятся лишние объекты и почему я не могу никак их отловить?
Здравствуйте.
Если вкратце - сайт представляет собой доску с кучей картинок, которые по нему можно двигать. Вот объект, который отвечает за появление картинки на странице.
const field_con = { fig_list: [], addFigure(obj){ if (obj.id != undefined) { this.fig_list[obj.id] = document.createElement('img'); that = this.fig_list[obj.id]; } else { this.fig_list[this.fig_list.length] = document.createElement('img'); that = this.fig_list[this.fig_list.length-1]; that.id = this.fig_list.length-1; } that.orig = obj; that.name = obj.name; that.title = obj.name; that.src = "http://127.0.0.1:8000/static/" + obj.src; that.orig.rota = (that.orig.rota == undefined) ? (0) : that.orig.rota; that.eventAnchor = 'figure'; that.x_cord = obj.x; that.y_cord = obj.y; console.log(obj.x); that.style.top = that.y_cord + 'px'; that.style.left = that.x_cord + 'px'; that.style.position = 'absolute'; that.style.transform = `rotate(${that.orig.rota}deg)`; that.bound_fig = obj.bound_fig; if (that.bound_fig != undefined) that.bound_fig.onField = this.fig_list[that.id]; that.bound_unit = obj.bound_unit; that.onmousedown = mouseDownWrapperUnit; if (that.bound_unit != undefined) that.onmouseover = highlight_unit; that.onmouseout = highlight_unit_stop; document.body.append(that); return that; }, } |
const field_con = { fig_list: [], addFigure(obj){ if (obj.id != undefined) { this.fig_list[obj.id] = document.createElement('img'); that = this.fig_list[obj.id]; } else { this.fig_list[this.fig_list.length] = document.createElement('img'); that = this.fig_list[this.fig_list.length-1]; that.id = this.fig_list.length-1; } that.orig = obj; that.name = obj.name; that.title = obj.name; that.src = "http://127.0.0.1:8000/static/" + obj.src; that.orig.rota = (that.orig.rota == undefined) ? (0) : that.orig.rota; that.eventAnchor = 'figure'; that.x_cord = obj.x; that.y_cord = obj.y; console.log(obj.x); that.style.top = that.y_cord + 'px'; that.style.left = that.x_cord + 'px'; that.style.position = 'absolute'; that.style.transform = `rotate(${that.orig.rota}deg)`; that.bound_fig = obj.bound_fig; if (that.bound_fig != undefined) that.bound_fig.onField = this.fig_list[that.id]; that.bound_unit = obj.bound_unit; that.onmousedown = mouseDownWrapperUnit; if (that.bound_unit != undefined) that.onmouseover = highlight_unit; that.onmouseout = highlight_unit_stop; document.body.append(that); return that; }, }
У меня заранее подгружено одно изображение, которое имеет немного замороченную, но функцию Drag'nDrop'а (вот его код):
function dragndrop(event, target) { that = target; that.ondragstart = function() {return false;}; that.style.position = 'absolute'; that.style.zIndex = 1000; document.body.append(that); corr_x = event.pageX - that.getBoundingClientRect().x; corr_y = event.pageY - that.getBoundingClientRect().y; moveAt(event.pageX, event.pageY); if (game_con.unitMoverActive == true) { for (c of game_con.initials) if (c.whom == that) { startpoint = c; } }; function moveAt(pageX, pageY) { that.x_cord = (pageX - corr_x); that.style.left = that.x_cord + 'px'; that.y_cord = (pageY - corr_y); that.style.top = that.y_cord + 'px'; findAngle(200, 200, that.x_cord, that.y_cord); } function onMouseMove(event) { if ((game_con.unitMoverActive == false)||(rangeMeasure(that.initialMovementX, that.initialMovementY, that.x_cord, that.y_cord)<that.bound_unit.move)) { moveAt(event.pageX, event.pageY, that); } } document.addEventListener('mousemove', onMouseMove); that.onwheel = wheel_rotate; that.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); that.style.zIndex = 500; that.onmouseup = null; that.onwheel = null; }; }; |
function dragndrop(event, target) { that = target; that.ondragstart = function() {return false;}; that.style.position = 'absolute'; that.style.zIndex = 1000; document.body.append(that); corr_x = event.pageX - that.getBoundingClientRect().x; corr_y = event.pageY - that.getBoundingClientRect().y; moveAt(event.pageX, event.pageY); if (game_con.unitMoverActive == true) { for (c of game_con.initials) if (c.whom == that) { startpoint = c; } }; function moveAt(pageX, pageY) { that.x_cord = (pageX - corr_x); that.style.left = that.x_cord + 'px'; that.y_cord = (pageY - corr_y); that.style.top = that.y_cord + 'px'; findAngle(200, 200, that.x_cord, that.y_cord); } function onMouseMove(event) { if ((game_con.unitMoverActive == false)||(rangeMeasure(that.initialMovementX, that.initialMovementY, that.x_cord, that.y_cord)<that.bound_unit.move)) { moveAt(event.pageX, event.pageY, that); } } document.addEventListener('mousemove', onMouseMove); that.onwheel = wheel_rotate; that.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); that.style.zIndex = 500; that.onmouseup = null; that.onwheel = null; }; };
Недавно, я попытался реализовать функцию, которая должна определять угол одного объекта относительно другого (findAngle), и в качестве теста решил немного её расширить - теперь она должна рисовать след за перетаскиваемым объектом, но если объект вышел за определённый радиус, то след "упрётся" в невидимую стену и не сможет её покинуть. Вот код функции:
function findAngle(x0, y0, x, y) { r = rangeMeasure(x0, y0, x, y); cx = Math.acos((x - x0) / r); cy = Math.asin((y - y0) / r); // console.log(Math.trunc(cx*57,2958), ' ', Math.trunc(cy*57,2958)); if (r>100) { r = 100; }; zx = r * Math.cos(cx) + x0; zy = r * Math.sin(cy) + y0; obj = { src: 'dot.png', x: zx, y: zy, }; console.log(obj.x, ' ', obj.y); if (r>=100) { rra = field_con.addFigure(obj); console.log(rra); if (rangeMeasure(200, 200, rra.x, rra.y)>r) rra.remove(); } } |
function findAngle(x0, y0, x, y) { r = rangeMeasure(x0, y0, x, y); cx = Math.acos((x - x0) / r); cy = Math.asin((y - y0) / r); // console.log(Math.trunc(cx*57,2958), ' ', Math.trunc(cy*57,2958)); if (r>100) { r = 100; }; zx = r * Math.cos(cx) + x0; zy = r * Math.sin(cy) + y0; obj = { src: 'dot.png', x: zx, y: zy, }; console.log(obj.x, ' ', obj.y); if (r>=100) { rra = field_con.addFigure(obj); console.log(rra); if (rangeMeasure(200, 200, rra.x, rra.y)>r) rra.remove(); } }
Однако, появляется проблема. Сам по себе код работает, но только появляется сразу два следа - "правильный", упёршийся в "стену", и тот, который продолжает следовать за картинкой:
Попытки отследить, откуда возникают призрачные точки успехом не увенчались: Если закоментировать вызов addFigure в функции findAngle, то перестают рисоваться вообще любые следы, а попытка отследить возникновение этих точек не приводит к чему-либо осмысленному (смотреть на точку с id 4):
Собственно, а откуда вообще берутся эти призрачные точки?
Если необходимо, то вот полный код скрипта: https://pastebin.com/pKsNnKjN
Дополнительно:
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос


Причина появления лишних объектов в вашем коде может быть вызвана несколькими факторами. Один из возможных сценариев - это утечка памяти. Утечка памяти происходит, когда объекты создаются, но не уничтожаются после использования, что приводит к накоплению лишних объектов в памяти.
Для того чтобы понять, почему вы не можете отловить эти лишние объекты, вам следует использовать инструменты для анализа памяти, такие как xdebug или Valgrind. Эти инструменты позволяют выявить точные места в вашем коде, где происходит утечка памяти и где создаются лишние объекты.
Также стоит убедиться, что вы правильно управляете жизненным циклом объектов. Например, если вы создаете объекты внутри цикла, но не уничтожаете их после завершения цикла, это может привести к утечке памяти. Убедитесь, что вы вызываете метод unset() для удаления объектов, когда они больше не нужны.
Еще одной возможной причиной появления лишних объектов может быть некорректное использование ссылок на объекты. Если вы передаете объекты по ссылке и забываете обнулить ссылку после использования, это также может привести к утечке памяти.
В целом, для того чтобы избежать появления лишних объектов и утечек памяти, важно следить за правильным управлением памятью и жизненным циклом объектов в вашем коде. Используйте инструменты для анализа памяти, чтобы выявить проблемные участки кода и исправить их.