Конечно! Ниже приведён ваш скрипт с добавленными console.log для отладки проблемы с видео. Я отметил моменты, куда были добавлены строки вывода:
(() => {
const field = document.getElementById('field');
const clearBtn = document.getElementById('clearZones');
const manualWidth = document.getElementById('manualWidth');
const manualHeight = document.getElementById('manualHeight');
const applySizeBtn = document.getElementById('applySize');
const sizeMsg = document.getElementById('sizeMsg');
let zones = [];
let videosList = [];
let selectionStart = null;
let selectionDiv = null;
let activeZone = null;
let dragOffset = {x:0, y:0};
let resizeDir = null;
let selectedZone = null; // Текущая выделенная зона
function genId() {
return 'zone-' + Math.random().toString(36).substr(2, 9);
}
async function saveZones() {
try {
await fetch('zones_api.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(zones)
});
console.log('Зоны сохранены', zones); // лог для сохранения зон
} catch(e) {
console.error('Ошибка сохранения зон:', e);
}
}
async function loadZones() {
try {
let res = await fetch('zones_api.php');
if (!res.ok) throw new Error('Ошибка загрузки');
zones = await res.json();
console.log('Зоны загружены:', zones); // Лог загрузки зон
renderZones();
} catch (e) {
console.error(e);
zones = [];
renderZones();
}
}
// Загрузка списка видео с сервера
async function loadVideoList() {
try {
let res = await fetch('video_list.php');
if (!res.ok) throw new Error('Не удалось загрузить список видео');
videosList = await res.json();
console.log('Список видео загружен:', videosList); // <<< Лог загрузки списка видео
} catch (e) {
console.error(e);
videosList = [];
}
}
function selectZone(zone) {
selectedZone = zone;
manualWidth.value = Math.round(zone.width);
manualHeight.value = Math.round(zone.height);
sizeMsg.textContent = '';
}
function createZoneElement(zone) {
let el = document.createElement('div');
el.className = 'zone';
el.dataset.id = zone.id;
el.style.left = zone.x + 'px';
el.style.top = zone.y + 'px';
el.style.width = zone.width + 'px';
el.style.height = zone.height + 'px';
// Кнопка удаления слева
let delBtn = document.createElement('div');
delBtn.className = 'zone-delete-btn';
delBtn.title = 'Удалить зону';
delBtn.textContent = '×';
delBtn.style.position = 'absolute';
delBtn.style.top = '2px';
delBtn.style.left = '2px';
delBtn.style.cursor = 'pointer';
delBtn.style.color = '#fff';
delBtn.style.background = '#dc3545';
delBtn.style.fontWeight = 'bold';
delBtn.style.borderRadius = '50%';
delBtn.style.width = '18px';
delBtn.style.height = '18px';
delBtn.style.lineHeight = '18px';
delBtn.style.textAlign = 'center';
delBtn.style.userSelect = 'none';
delBtn.style.zIndex = '30';
delBtn.addEventListener('click', (e) => {
e.stopPropagation();
zones = zones.filter(z => z.id !== zone.id);
if (selectedZone && selectedZone.id === zone.id) {
selectedZone = null;
manualWidth.value = '';
manualHeight.value = '';
sizeMsg.textContent = '';
}
saveZones();
renderZones();
});
el.appendChild(delBtn);
// Контейнер для имени и размеров, с отступом слева
let infoContainer = document.createElement('div');
infoContainer.style.display = 'flex';
infoContainer.style.justifyContent = 'space-between';
infoContainer.style.alignItems = 'center';
infoContainer.style.width = 'calc(100% - 28px)';
infoContainer.style.marginLeft = '28px';
let label = document.createElement('div');
label.className = 'zone-label';
label.contentEditable = true;
label.innerText = zone.name || 'Без названия';
label.title = 'Двойной клик для редактирования имени';
label.style.flexGrow = '1';
label.style.paddingRight = '5px';
label.style.whiteSpace = 'nowrap';
label.style.overflow = 'hidden';
label.style.textOverflow = 'ellipsis';
label.addEventListener('blur', () => {
zone.name = label.innerText.trim() || 'Без названия';
saveZones();
});
label.addEventListener('keydown', e => {
if(e.key === 'Enter') {
e.preventDefault();
label.blur();
}
});
infoContainer.appendChild(label);
let sizeDisplay = document.createElement('div');
sizeDisplay.className = 'zone-size';
sizeDisplay.style.flexShrink = '0';
sizeDisplay.style.fontSize = '12px';
sizeDisplay.style.color = '#004a99';
sizeDisplay.style.whiteSpace = 'nowrap';
infoContainer.appendChild(sizeDisplay);
el.appendChild(infoContainer);
function updateZoneSize() {
sizeDisplay.textContent = `${Math.round(zone.width)}×${Math.round(zone.height)} px`;
}
updateZoneSize();
const resizeHandlesPos = ['nw','n','ne','e','se','s','sw','w'];
resizeHandlesPos.forEach(pos => {
let handle = document.createElement('div');
handle.className = 'resize-handle ' + pos;
handle.dataset.dir = pos;
el.appendChild(handle);
});
label.addEventListener('dblclick', () => label.focus());
el.addEventListener('mousedown', e => {
if(e.target.classList.contains('resize-handle')) {
activeZone = zone;
resizeDir = e.target.dataset.dir;
} else if(e.target === label) {
return;
} else {
activeZone = zone;
resizeDir = null;
dragOffset.x = e.clientX - el.getBoundingClientRect().left;
dragOffset.y = e.clientY - el.getBoundingClientRect().top;
}
e.stopPropagation();
e.preventDefault();
});
// Выделение зоны по клику
el.addEventListener('click', e => {
e.stopPropagation();
selectZone(zone);
});
// Видео или селект для выбора видео
let videoContainer = document.createElement('div');
videoContainer.className = 'zone-video-container';
videoContainer.style.flexGrow = '1';
videoContainer.style.padding = '4px';
videoContainer.style.marginTop = '4px';
videoContainer.style.width = '100%';
videoContainer.style.height = 'calc(100% - 40px)';
videoContainer.style.boxSizing = 'border-box';
// always create select, if there is a selected video it will appear in video
let sel = document.createElement('select');
sel.style.width = '100%';
let defaultOpt = document.createElement('option');
defaultOpt.value = '';
defaultOpt.textContent = 'Выберите видео для зоны';
sel.appendChild(defaultOpt);
videosList.forEach(src => {
let opt = document.createElement('option');
opt.value = src;
opt.textContent = src.replace(/^.*[\\\/]/, '');
sel.appendChild(opt);
});
console.log('Создан селект видео для зоны', zone.id, 'с опциями:', videosList); // <<< лог создания селекта
sel.value = zone.videoSrc || '';
sel.addEventListener('change', () => {
const val = sel.value;
console.log('Выбрано видео для зоны', zone.id, ':', val); // <<< лог выбора видео
zone.videoSrc = val || null;
saveZones();
// Обновить видео плеер
updateVideo();
});
videoContainer.appendChild(sel);
// функция для обновления видео
function updateVideo() {
// находим видео в контейнере, если есть — удаляем
let existingVideo = videoContainer.querySelector('video');
if(existingVideo){
existingVideo.remove();
console.log('Удалено старое видео из зоны', zone.id); // <<< лог удаления предыдущего видео
}
if(zone.videoSrc){
console.log('Создаём видео в зоне', zone.id, 'с источником:', zone.videoSrc); // <<< лог создания видео
let video = document.createElement('video');
video.src = zone.videoSrc;
video.controls = true;
video.style.width = '100%';
video.style.height = '100%';
video.style.display = 'block';
videoContainer.appendChild(video);
sel.style.display = 'none';
} else {
sel.style.display = '';
}
}
updateVideo();
el._updateZoneSize = updateZoneSize;
return el;
}
function renderZones() {
field.querySelectorAll('.zone').forEach(z => z.remove());
zones.forEach(zone => {
let el = createZoneElement(zone);
field.appendChild(el);
});
}
function addZoneFromRect(x1, y1, x2, y2) {
let left = Math.min(x1, x2);
let top = Math.min(y1, y2);
let right = Math.max(x1, x2);
let bottom = Math.max(y1, y2);
left = Math.max(left, 0);
top = Math.max(top, 0);
right = Math.min(right, field.clientWidth);
bottom = Math.min(bottom, field.clientHeight);
let width = right - left;
let height = bottom - top;
if(width < 20 || height < 20) return;
const newZone = {
id: genId(),
x: left,
y: top,
width: width,
height: height,
name: 'Без названия',
videoSrc: null
};
zones.push(newZone);
saveZones();
renderZones();
}
field.addEventListener('mousedown', e => {
if(e.target !== field) return;
selectionStart = {x: e.offsetX, y: e.offsetY};
selectionDiv = document.createElement('div');
selectionDiv.className = 'selection-rect';
selectionDiv.style.left = selectionStart.x + 'px';
selectionDiv.style.top = selectionStart.y + 'px';
selectionDiv.style.width = '0px';
selectionDiv.style.height = '0px';
field.appendChild(selectionDiv);
e.preventDefault();
});
field.addEventListener('mousemove', e => {
if (!selectionStart) return;
let x = e.offsetX;
let y = e.offsetY;
let left = Math.min(selectionStart.x, x);
let top = Math.min(selectionStart.y, y);
let width = Math.abs(selectionStart.x - x);
let height = Math.abs(selectionStart.y - y);
selectionDiv.style.left = left + 'px';
selectionDiv.style.top = top + 'px';
selectionDiv.style.width = width + 'px';
selectionDiv.style.height = height + 'px';
e.preventDefault();
});
field.addEventListener('mouseup', e => {
if (!selectionStart) return;
addZoneFromRect(selectionStart.x, selectionStart.y, e.offsetX, e.offsetY);
selectionDiv.remove();
selectionDiv = null;
selectionStart = null;
e.preventDefault();
});
document.addEventListener('mouseup', e => {
activeZone = null;
resizeDir = null;
});
document.addEventListener('mousemove', e => {
if (!activeZone) return;
let zoneEl = field.querySelector(`.zone[data-id="${activeZone.id}"]`);
if (!zoneEl) return;
let fieldRect = field.getBoundingClientRect();
if (resizeDir) {
let dx = e.clientX - fieldRect.left;
let dy = e.clientY - fieldRect.top;
let minSize = 20;
let newLeft = activeZone.x;
let newTop = activeZone.y;
let newWidth = activeZone.width;
let newHeight = activeZone.height;
if (resizeDir.includes('n')) {
newTop = Math.min(dy, activeZone.y + activeZone.height - minSize);
newHeight = activeZone.height - (newTop - activeZone.y);
}
if (resizeDir.includes('s')) {
newHeight = Math.max(minSize, dy - activeZone.y);
}
if (resizeDir.includes('w')) {
newLeft = Math.min(dx, activeZone.x + activeZone.width - minSize);
newWidth = activeZone.width - (newLeft - activeZone.x);
}
if (resizeDir.includes('e')) {
newWidth = Math.max(minSize, dx - activeZone.x);
}
if (newLeft < 0) {
newWidth -= -newLeft;
newLeft = 0;
}
if (newTop < 0) {
newHeight -= -newTop;
newTop = 0;
}
if (newLeft + newWidth > field.clientWidth) {
newWidth = field.clientWidth - newLeft;
}
if (newTop + newHeight > field.clientHeight) {
newHeight = field.clientHeight - newTop;
}
activeZone.x = newLeft;
activeZone.y = newTop;
activeZone.width = newWidth;
activeZone.height = newHeight;
zoneEl.style.left = newLeft + 'px';
zoneEl.style.top = newTop + 'px';
zoneEl.style.width = newWidth + 'px';
zoneEl.style.height = newHeight + 'px';
if (typeof zoneEl._updateZoneSize === 'function') {
zoneEl._updateZoneSize();
}
saveZones();
} else {
let x = e.clientX - dragOffset.x - fieldRect.left;
let y = e.clientY - dragOffset.y - fieldRect.top;
x = Math.max(0, Math.min(x, field.clientWidth - activeZone.width));
y = Math.max(0, Math.min(y, field.clientHeight - activeZone.height));
activeZone.x = x;
activeZone.y = y;
zoneEl.style.left = x + 'px';
zoneEl.style.top = y + 'px';
if (typeof zoneEl._updateZoneSize === 'function') {
zoneEl._updateZoneSize();
}
saveZones();
}
});
clearBtn.addEventListener('click', () => {
if (confirm('Очистить все зоны?')) {
zones = [];
selectedZone = null;
manualWidth.value = '';
manualHeight.value = '';
sizeMsg.textContent = '';
saveZones();
renderZones();
}
});
field.addEventListener('click', e => {
if (e.target === field) {
selectedZone = null;
manualWidth.value = '';
manualHeight.value = '';
sizeMsg.textContent = '';
}
});
applySizeBtn.addEventListener('click', () => {
if (!selectedZone) {
sizeMsg.textContent = 'Выберите зону для изменения.';
return;
}
let w = parseInt(manualWidth.value);
let h = parseInt(manualHeight.value);
if (isNaN(w) || isNaN(h) || w < 20 || w > 768 || h < 20 || h > 512) {
sizeMsg.textContent = 'Введите корректные размеры: ширина 20-768, высота 20-512.';
return;
}
selectedZone.width = w;
selectedZone.height = h;
if(selectedZone.x + w > field.clientWidth) selectedZone.x = field.clientWidth - w;
if(selectedZone.y + h > field.clientHeight) selectedZone.y = field.clientHeight - h;
sizeMsg.textContent = '';
saveZones();
renderZones();
manualWidth.value = Math.round(selectedZone.width);
manualHeight.value = Math.round(selectedZone.height);
});
const style = document.createElement('style');
style.textContent = `
.zone {
position: absolute;
background-color: rgba(0,123,255,0.3);
border: 2px solid #007bff;
box-sizing: border-box;
cursor: move;
user-select: none;
z-index: 10;
display: flex;
flex-direction: column;
padding: 2px 2px 0 2px;
}
.zone-label {
background: rgba(255,255,255,0.8);
border-radius: 4px;
padding: 0 5px;
max-width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
cursor: text;
user-select: text;
font-size: 14px;
line-height: 20px;
}
.zone-size {
font-weight: normal;
font-size: 12px;
color: #004a99;
white-space: nowrap;
padding-left: 6px;
user-select: none;
align-self: flex-end;
margin-top: 2px;
}
.zone-delete-btn {
position: absolute;
top: 2px;
left: 2px;
cursor: pointer;
color: #fff;
background: #dc3545;
font-weight: bold;
border-radius: 50%;
width: 18px;
height: 18px;
line-height: 18px;
text-align: center;
user-select: none;
z-index: 30;
}
.zone-delete-btn:hover {
background: #c82333;
}
.resize-handle {
position: absolute;
width: 10px;
height: 10px;
background: #007bff;
border: 1px solid #004a99;
box-sizing: border-box;
z-index: 20;
cursor: pointer;
border-radius: 2px;
}
.resize-handle.nw { top: -5px; left: -5px; cursor: nwse-resize; }
.resize-handle.n { top: -5px; left: 50%; transform: translateX(-50%); cursor: ns-resize; }
.resize-handle.ne { top: -5px; right: -5px; cursor: nesw-resize; }
.resize-handle.e { top: 50%; right: -5px; transform: translateY(-50%); cursor: ew-resize; }
.resize-handle.se { bottom: -5px; right: -5px; cursor: nwse-resize; }
.resize-handle.s { bottom: -5px; left: 50%; transform: translateX(-50%); cursor: ns-resize; }
.resize-handle.sw { bottom: -5px; left: -5px; cursor: nesw-resize; }
.resize-handle.w { top: 50%; left: -5px; transform: translateY(-50%); cursor: ew-resize; }
.selection-rect {
position: absolute;
border: 2px dashed #007bff;
background-color: rgba(0, 123, 255, 0.15);
pointer-events: none;
z-index: 1000;
}
.zone-video-container {
flex-grow: 1;
margin-top: 4px;
width: 100%;
height: calc(100% - 64px);
box-sizing: border-box;
}
.zone-video-container select {
width: 100%;
padding: 4px 6px;
font-size: 14px;
}
.zone-video-container video {
background: black;
width: 100%;
height: 100%;
display: block;
}
.size-manual input {
padding: 3px 6px;
font-size: 14px;
}
`;
document.head.appendChild(style);
loadVideoList().then(loadZones);
})();
Теперь в консоли вы увидите:
- Когда список видео загружен (
"Список видео загружен:").
- Какие видео доступны в выпадающем списке каждой зоны (
"Создан селект видео для зоны ...")
- Какое видео выбрано для зоны (
"Выбрано видео для зоны ...").
- Удаляется ли старое видео перед созданием нового (
"Удалено старое видео из зоны ...").
- Создается ли видеоэлемент и с каким src (
"Создаём видео в зоне ... с источником: ...").
- Когда зоны сохраняются и загружаются.
Запустите ваш проект и посмотрите консоль, скопируйте сюда вывод — так я помогу понять, где именно проблема с видео. Если видео не появляются, возможно, что список видео пуст или пути к видео неправильные.
Если нужно, могу помочь с дополнительной отладкой!