Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

Update my code whilst keeping all current features with these changes, move the 'export…

  1. User

    Update my code whilst keeping all current features with these changes, move the 'export settings' panel below the other panels and have it appear horizontally across the page.

    Redo the entire 'Layers List' so there is are buttons above the listed layers, such as, '+' to add a new layer, 'up ' and 'down' buttons to re-order the current layer, an 'X' to remove the currently selected layer (triggers a 'Are you sure' popup) and also an 'eye' which toggles 'show and hide' currently selected layer. Default is 'show' layer.

        .layer-control { border: 1px dashed #e0e0e0; padding: 10px; margin-bottom: 15px; background-color: #fafafa; border-radius: 5px; position: relative; }
        .layer-control h4 { margin-top: 0; margin-bottom: 10px; display: inline-block; }
        .layer-actions { float: right; }
        .layer-actions button { background-color: #6c757d; margin-left: 5px; }
        .layer-actions button.remove-layer-btn { background-color: #dc3545; }
        .layer-actions button.select-drag-btn { background-color: #28a745; }
        .layer-actions button:hover { background-color: #5a6268; }
        .layer-actions button.remove-layer-btn:hover { background-color: #c82333; }
        .layer-actions button.select-drag-btn:hover { background-color: #218838; }
    
        canvas { border: 1px solid #ccc; background-color: #eee; display: block; margin: 20px auto; max-width: 100%; height: auto; cursor: grab; }
        canvas.dragging { cursor: grabbing; }
    
        .preview-controls, .global-parallax-controls, .export-options { display: flex; align-items: center; justify-content: center; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
        .export-options > div { flex: 1; min-width: 150px; }
        .exported-images { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-top: 20px; max-height: 200px; overflow-y: auto; border: 1px solid #eee; padding: 10px; border-radius: 5px; }
        .exported-images img { max-width: 100px; height: auto; border: 1px solid #ddd; }
        #finalLenticularImage { max-width: 100%; height: auto; border: 1px solid #ddd; display: none; margin-top: 20px; }
        #downloadFinalLenticular { text-align: center; display: block; margin-top: 10px; color: #007bff; text-decoration: none; }
        #downloadFinalLenticular:hover { text-decoration: underline; }
    
        .processing-message {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 20px 40px;
            border-radius: 8px;
            z-index: 1000;
            font-size: 1.2em;
        }
        .processing-message.active {
            display: block;
        }
    </style>
    
    <div class="container">
        <div class="panel">
            <h2>Layers</h2>
            <div id="layersContainer">
                </div>
            <button id="addLayerBtn">Add Layer</button>
        </div>
    
        <div class="panel">
            <h2>Global Parallax</h2>
            <div class="global-parallax-controls">
                <label for="bgParallax">Background Parallax (Intensity):</label>
                <input type="range" id="bgParallax" min="-100" max="100" value="-50">
                <span id="bgParallaxValue">-50</span>
            </div>
            <div class="global-parallax-controls">
                <label for="fgParallax">Foreground Parallax (Intensity):</label>
                <input type="range" id="fgParallax" min="-100" max="100" value="50">
                <span id="fgParallaxValue">50</span>
            </div>
            <h2>Preview & Angle</h2>
            <canvas id="lenticularPreviewCanvas"></canvas>
            <div class="preview-controls">
                <label for="totalViewingAngleInput">Total Viewing Angle (degrees):</label>
                <input type="number" id="totalViewingAngleInput" value="40" min="5" max="120" step="1">
                <button id="applyViewingAngleBtn">Apply Angle</button>
            </div>
            <div class="preview-controls">
                <label for="viewingAngleInput">Live View (Degrees from Center):</label>
                <input type="range" id="viewingAngleInput" min="-20" max="20" value="0">
                <span id="viewingAngleValue">0</span>
            </div>
            <div class="preview-controls">
                <button id="startPreviewBtn">Start Loop</button>
                <button id="stopPreviewBtn">Stop Loop</button>
            </div>
        </div>
    
        <div class="panel">
            <h2>Export Settings</h2>
            <div class="export-options">
                <div>
                    <label for="lpiInput">LPI (Lenses Per Inch):</label>
                    <input type="number" id="lpiInput" value="30" min="10" max="200">
                </div>
                <div>
                    <label for="outputDpiInput">Output DPI (Print):</label>
                    <input type="number" id="outputDpiInput" value="300" min="72" max="1200">
                </div>
            </div>
            <label for="framesInput">Number of Frames:</label>
            <input type="number" id="framesInput" value="20" min="2" max="100">
    
            <button id="exportFramesBtn">Generate Frames</button>
            <div class="exported-images" id="exportedFramesContainer"></div>
    
            <button id="interlaceAndExportBtn">Interlace & Export Final Image</button>
            <h3>Final Lenticular:</h3>
            <img id="finalLenticularImage" src="" alt="Final Lenticular Image">
            <a id="downloadFinalLenticular" download="final_lenticular.png" style="display: none;">Download Final</a>
        </div>
    </div>
    <div id="processingMessage" class="processing-message">Processing... Please wait.</div>
    
    <script>
        const $ = id => document.getElementById(id);
    
        const layers = [];
        let nextLayerId = 0;
        const previewCanvas = $('lenticularPreviewCanvas');
        const ctx = previewCanvas.getContext('2d');
    
        const totalViewingAngleInput = $('totalViewingAngleInput');
        const applyViewingAngleBtn = $('applyViewingAngleBtn');
        const viewingAngleInput = $('viewingAngleInput');
        const viewingAngleValueSpan = $('viewingAngleValue');
        const startPreviewBtn = $('startPreviewBtn');
        const stopPreviewBtn = $('stopPreviewBtn');
        const addLayerBtn = $('addLayerBtn');
        const layersContainer = $('layersContainer');
        const lpiInput = $('lpiInput');
        const outputDpiInput = $('outputDpiInput');
        const framesInput = $('framesInput');
        const exportFramesBtn = $('exportFramesBtn');
        const exportedFramesContainer = $('exportedFramesContainer');
        const interlaceAndExportBtn = $('interlaceAndExportBtn');
        const finalLenticularImage = $('finalLenticularImage');
        const downloadFinalLenticular = $('downloadFinalLenticular');
        const bgParallaxSlider = $('bgParallax');
        const bgParallaxValueSpan = $('bgParallaxValue');
        const fgParallaxSlider = $('fgParallax');
        const fgParallaxValueSpan = $('fgParallaxValue');
        const processingMessage = $('processingMessage'); // New
    
        let animationFrameId = null;
        let currentLiveViewAngle = 0;
        let totalViewingAngle = 40; // Initial default total viewing angle
    
        const previewSpeed = 0.5;
        let previewDirection = 1;
    
        const exportedFrames = [];
        let baseImageWidth = 0;
        let baseImageHeight = 0;
    
        // --- Dragging State ---
        let isDragging = false;
        let draggedLayerId = null;
        let lastMouseX = 0;
        let lastMouseY = 0;
    
        // --- Helper for UI Feedback ---
        function setProcessing(isLoading) {
            if (isLoading) {
                processingMessage.classList.add('active');
                exportFramesBtn.disabled = true;
                interlaceAndExportBtn.disabled = true;
            } else {
                processingMessage.classList.remove('active');
                exportFramesBtn.disabled = false;
                interlaceAndExportBtn.disabled = false;
            }
        }
    
        // --- Event Listeners ---
        viewingAngleInput.addEventListener('input', () => {
            currentLiveViewAngle = parseFloat(viewingAngleInput.value);
            viewingAngleValueSpan.textContent = Math.round(currentLiveViewAngle);
            drawLenticularPreview(currentLiveViewAngle);
        });
        applyViewingAngleBtn.addEventListener('click', applyTotalViewingAngle);
        startPreviewBtn.addEventListener('click', startPreviewAnimation);
        stopPreviewBtn.addEventListener('click', stopPreviewAnimation);
        addLayerBtn.addEventListener('click', addLayer);
        exportFramesBtn.addEventListener('click', async () => {
            setProcessing(true);
            try {
                await generateAndExportFrames();
            } finally {
                setProcessing(false);
            }
        });
        interlaceAndExportBtn.addEventListener('click', async () => {
            setProcessing(true);
            try {
                await interlaceFrames();
            } finally {
                setProcessing(false);
            }
        });
    
        bgParallaxSlider.addEventListener('input', () => {
            bgParallaxValueSpan.textContent = bgParallaxSlider.value;
            drawLenticularPreview(currentLiveViewAngle);
        });
        fgParallaxSlider.addEventListener('input', () => {
            fgParallaxValueSpan.textContent = fgParallaxSlider.value;
            drawLenticularPreview(currentLiveViewAngle);
        });
    
        // --- Canvas Dragging Event Listeners ---
        previewCanvas.addEventListener('mousedown', startDrag);
        previewCanvas.addEventListener('mousemove', drag);
        previewCanvas.addEventListener('mouseup', endDrag);
        previewCanvas.addEventListener('mouseleave', endDrag);
    
        // --- Dragging Functions ---
        function startDrag(e) {
            if (draggedLayerId === null) return;
    
            isDragging = true;
            previewCanvas.classList.add('dragging');
            lastMouseX = e.clientX;
            lastMouseY = e.clientY;
        }
    
        function drag(e) {
            if (!isDragging) return;
    
            const rect = previewCanvas.getBoundingClientRect();
            const scaleX = previewCanvas.width / rect.width;
            const scaleY = previewCanvas.height / rect.height;
    
            const dx = (e.clientX - lastMouseX) * scaleX;
            const dy = (e.clientY - lastMouseY) * scaleY;
    
            const layer = layers.find(l => l.id === draggedLayerId);
            if (layer) {
                layer.offsetX += dx;
                layer.offsetY += dy;
                const layerControl = document.querySelector(`.layer-control[data-layer-id="${draggedLayerId}"]`);
                layerControl.querySelector(`#offsetX${draggedLayerId}`).value = Math.round(layer.offsetX);
                layerControl.querySelector(`#offsetXValue${draggedLayerId}`).textContent = Math.round(layer.offsetX);
                layerControl.querySelector(`#offsetY${draggedLayerId}`).value = Math.round(layer.offsetY);
                layerControl.querySelector(`#offsetYValue${draggedLayerId}`).textContent = Math.round(layer.offsetY);
                drawLenticularPreview(currentLiveViewAngle);
            }
    
            lastMouseX = e.clientX;
            lastMouseY = e.clientY;
        }
    
        function endDrag() {
            isDragging = false;
            previewCanvas.classList.remove('dragging');
        }
    
        // --- Viewing Angle Logic ---
        function applyTotalViewingAngle() {
            const newTotalAngle = parseFloat(totalViewingAngleInput.value);
            if (isNaN(newTotalAngle) || newTotalAngle <= 0) {
                alert("Please enter a valid positive number for Total Viewing Angle.");
                return;
            }
            totalViewingAngle = newTotalAngle;
    
            viewingAngleInput.min = -totalViewingAngle / 2;
            viewingAngleInput.max = totalViewingAngle / 2;
            viewingAngleInput.value = 0;
    
            currentLiveViewAngle = 0;
            viewingAngleValueSpan.textContent = 0;
            drawLenticularPreview(currentLiveViewAngle);
        }
    
        // --- Layer Management ---
        function createLayerControlHtml(layerId) {
            return `
                <div class="layer-control" data-layer-id="${layerId}">
                    <h4>Layer ${layerId + 1}</h4>
                    <div class="layer-actions">
                        <button class="move-up-btn" data-layer-id="${layerId}">&#9650; Up</button>
                        <button class="move-down-btn" data-layer-id="${layerId}">&#9660; Down</button>
                        <button class="select-drag-btn" data-layer-id="${layerId}">Drag</button>
                        <button class="remove-layer-btn" data-layer-id="${layerId}">Remove</button>
                    </div>
                    <label for="imageUpload${layerId}">Image (PNG/GIF for transparency):</label>
                    <input type="file" id="imageUpload${layerId}" accept="image/*">
    
                    <label for="offsetX${layerId}">Offset X:</label>
                    <input type="range" id="offsetX${layerId}" min="-1000" max="1000" value="0">
                    <span id="offsetXValue${layerId}">0</span>
    
                    <label for="offsetY${layerId}">Offset Y:</label>
                    <input type="range" id="offsetY${layerId}" min="-1000" max="1000" value="0">
                    <span id="offsetYValue${layerId}">0</span>
    
                    <label for="scale${layerId}">Scale (%):</label>
                    <input type="range" id="scale${layerId}" min="10" max="400" value="100">
                    <span id="scaleValue${layerId}">100</span>
                </div>
            `;
        }
    
        function addLayer() {
            const layerId = nextLayerId++;
            layersContainer.insertAdjacentHTML('beforeend', createLayerControlHtml(layerId));
    
            const newLayer = { id: layerId, image: null, offsetX: 0, offsetY: 0, scale: 100 };
            layers.push(newLayer);
    
            bindLayerControlEvents(layerId, newLayer);
            drawLenticularPreview(currentLiveViewAngle);
            updateLayerOrderUI();
        }
    
        function bindLayerControlEvents(layerId, layerData) {
            const layerControl = document.querySelector(`.layer-control[data-layer-id="${layerId}"]`);
            const imageUpload = layerControl.querySelector(`#imageUpload${layerId}`);
            const offsetXSlider = layerControl.querySelector(`#offsetX${layerId}`);
            const offsetYSlider = layerControl.querySelector(`#offsetY${layerId}`);
            const scaleSlider = layerControl.querySelector(`#scale${layerId}`);
            const offsetXValueSpan = layerControl.querySelector(`#offsetXValue${layerId}`);
            const offsetYValueSpan = layerControl.querySelector(`#offsetYValue${layerId}`);
            const scaleValueSpan = layerControl.querySelector(`#scaleValue${layerId}`);
            const removeBtn = layerControl.querySelector(`.remove-layer-btn`);
            const moveUpBtn = layerControl.querySelector(`.move-up-btn`);
            const moveDownBtn = layerControl.querySelector(`.move-down-btn`);
            const selectDragBtn = layerControl.querySelector(`.select-drag-btn`);
    
            imageUpload.addEventListener('change', (e) => handleImageUpload(e, layerId));
            offsetXSlider.addEventListener('input', () => {
                layerData.offsetX = parseFloat(offsetXSlider.value);
                offsetXValueSpan.textContent = layerData.offsetX;
                drawLenticularPreview(currentLiveViewAngle);
            });
            offsetYSlider.addEventListener('input', () => {
                layerData.offsetY = parseFloat(offsetYSlider.value);
                offsetYValueSpan.textContent = layerData.offsetY;
                drawLenticularPreview(currentLiveViewAngle);
            });
            scaleSlider.addEventListener('input', () => {
                layerData.scale = parseFloat(scaleSlider.value);
                scaleValueSpan.textContent = layerData.scale;
                drawLenticularPreview(currentLiveViewAngle);
            });
            removeBtn.addEventListener('click', () => removeLayer(layerId));
            moveUpBtn.addEventListener('click', () => moveLayer(layerId, -1));
            moveDownBtn.addEventListener('click', () => moveLayer(layerId, 1));
            selectDragBtn.addEventListener('click', () => setDraggedLayer(layerId));
        }
    
        function setDraggedLayer(layerId) {
            draggedLayerId = layerId;
            document.querySelectorAll('.layer-control').forEach(el => el.style.border = '1px dashed #e0e0e0');
            const selectedControl = document.querySelector(`.layer-control[data-layer-id="${layerId}"]`);
            if (selectedControl) {
                selectedControl.style.border = '2px solid #28a745';
            }
        }
    
        function removeLayer(layerIdToRemove) {
            const layerIndex = layers.findIndex(layer => layer.id === layerIdToRemove);
            if (layerIndex > -1) {
                layers.splice(layerIndex, 1);
                document.querySelector(`.layer-control[data-layer-id="${layerIdToRemove}"]`).remove();
                if (draggedLayerId === layerIdToRemove) {
                    draggedLayerId = null;
                }
                drawLenticularPreview(currentLiveViewAngle);
                updateLayerOrderUI();
            }
        }
    
        function moveLayer(layerIdToMove, direction) {
            const index = layers.findIndex(layer => layer.id === layerIdToMove);
            if (index === -1) return;
    
            const newIndex = index + direction;
            if (newIndex >= 0 && newIndex < layers.length) {
                const [movedLayer] = layers.splice(index, 1);
                layers.splice(newIndex, 0, movedLayer);
    
                renderLayerControls();
                drawLenticularPreview(currentLiveViewAngle);
                updateLayerOrderUI();
            }
        }
    
        function renderLayerControls() {
            layersContainer.innerHTML = '';
            layers.forEach(layer => {
                layersContainer.insertAdjacentHTML('beforeend', createLayerControlHtml(layer.id));
                bindLayerControlEvents(layer.id, layer);
                const layerControl = document.querySelector(`.layer-control[data-layer-id="${layer.id}"]`);
                layerControl.querySelector(`#offsetX${layer.id}`).value = layer.offsetX;
                layerControl.querySelector(`#offsetXValue${layer.id}`).textContent = layer.offsetX;
                layerControl.querySelector(`#offsetY${layer.id}`).value = layer.offsetY;
                layerControl.querySelector(`#offsetYValue${layer.id}`).textContent = layer.offsetY;
                layerControl.querySelector(`#scale${layer.id}`).value = layer.scale;
                layerControl.querySelector(`#scaleValue${layer.id}`).textContent = layer.scale;
    
                if (draggedLayerId === layer.id) {
                     layerControl.style.border = '2px solid #28a745';
                }
            });
        }
    
        function updateLayerOrderUI() {
            layers.forEach((layer, index) => {
                const layerControl = document.querySelector(`.layer-control[data-layer-id="${layer.id}"]`);
                const moveUpBtn = layerControl.querySelector('.move-up-btn');
                const moveDownBtn = layerControl.querySelector('.move-down-btn');
    
                if (moveUpBtn) moveUpBtn.disabled = (index === 0);
                if (moveDownBtn) moveDownBtn.disabled = (index === layers.length - 1);
            });
        }
    
        async function handleImageUpload(event, layerId) {
            const file = event.target.files[0];
            if (!file) return;
    
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = new Image();
                img.onload = () => {
                    const layer = layers.find(l => l.id === layerId);
                    if (layer) {
                        layer.image = img;
                        if (baseImageWidth === 0 || baseImageHeight === 0) {
                            baseImageWidth = img.width;
                            baseImageHeight = img.height;
                            previewCanvas.width = baseImageWidth;
                            previewCanvas.height = baseImageHeight;
                        }
                        drawLenticularPreview(currentLiveViewAngle);
                    }
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    
        // --- Rendering Logic ---
        function drawLenticularPreview(liveViewAngle) {
            ctx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
            // Draw a light gray background for the preview area,
            // which will show through if images have transparency.
            ctx.fillStyle = '#EEE';
            ctx.fillRect(0, 0, previewCanvas.width, previewCanvas.height);
    
    
            if (layers.every(l => l.image === null)) {
                ctx.font = '20px Arial';
                ctx.fillStyle = '#666';
                ctx.textAlign = 'center';
                ctx.fillText("Upload images to start", previewCanvas.width / 2, previewCanvas.height / 2);
                return;
            }
    
            const bgParallax = parseFloat(bgParallaxSlider.value);
            const fgParallax = parseFloat(fgParallaxSlider.value);
            const numLayers = layers.length;
    
            const minSliderAngle = parseFloat(viewingAngleInput.min);
            const maxSliderAngle = parseFloat(viewingAngleInput.max);
            const sliderRange = maxSliderAngle - minSliderAngle;
    
            let normalizedLiveViewAngle = 0;
            if (sliderRange > 0) {
                normalizedLiveViewAngle = (liveViewAngle - minSliderAngle) / sliderRange * 2 - 1;
            }
    
            // Layers are drawn in the order they appear in the 'layers' array (background to foreground)
            layers.forEach((layer, index) => {
                if (!layer.image) return;
    
                let layerParallax = 0;
                if (numLayers === 1) {
                    layerParallax = fgParallax;
                } else {
                    const t = index / (numLayers - 1);
                    layerParallax = bgParallax + (fgParallax - bgParallax) * t;
                }
    
                const normalizedParallax = layerParallax / 100;
    
                const maxPreviewShift = previewCanvas.width * 0.05;
                const shiftX = normalizedLiveViewAngle * normalizedParallax * maxPreviewShift;
    
                const scaledWidth = layer.image.width * (layer.scale / 100);
                const scaledHeight = layer.image.height * (layer.scale / 100);
    
                ctx.drawImage(
                    layer.image,
                    layer.offsetX + shiftX,
                    layer.offsetY,
                    scaledWidth,
                    scaledHeight
                );
            });
        }
    
        // --- Preview Animation ---
        function animatePreview() {
            const minAngle = parseFloat(viewingAngleInput.min);
            const maxAngle = parseFloat(viewingAngleInput.max);
    
            currentLiveViewAngle += previewDirection * previewSpeed;
    
            if (currentLiveViewAngle >= maxAngle || currentLiveViewAngle <= minAngle) {
                previewDirection *= -1;
                currentLiveViewAngle = Math.max(minAngle, Math.min(maxAngle, currentLiveViewAngle));
            }
    
            viewingAngleInput.value = currentLiveViewAngle;
            viewingAngleValueSpan.textContent = Math.round(currentLiveViewAngle);
            drawLenticularPreview(currentLiveViewAngle);
    
            animationFrameId = requestAnimationFrame(animatePreview);
        }
    
        function startPreviewAnimation() {
            if (!animationFrameId) {
                const minAngle = parseFloat(viewingAngleInput.min);
                const maxAngle = parseFloat(viewingAngleInput.max);
    
                previewDirection = (currentLiveViewAngle >= maxAngle - previewSpeed) ? -1 : 1;
                animatePreview();
            }
        }
    
        function stopPreviewAnimation() {
            cancelAnimationFrame(animationFrameId);
            animationFrameId = null;
        }
    
        // --- Export Frames ---
        async function generateAndExportFrames() {
            exportedFrames.length = 0;
            exportedFramesContainer.innerHTML = '';
    
            const numFrames = parseInt(framesInput.value, 10);
            if (isNaN(numFrames) || numFrames < 2) {
                alert("Please enter a valid number of frames (at least 2).");
                return;
            }
            if (baseImageWidth === 0 || baseImageHeight === 0) {
                alert("Please upload at least one image layer first to determine canvas size.");
                return;
            }
            previewCanvas.width = baseImageWidth;
            previewCanvas.height = baseImageHeight;
    
            const originalLiveViewAngle = currentLiveViewAngle;
            const minFrameAngle = parseFloat(viewingAngleInput.min);
            const maxFrameAngle = parseFloat(viewingAngleInput.max);
            const angleSpan = maxFrameAngle - minFrameAngle;
    
            const angleStep = angleSpan / (numFrames - 1);
    
            for (let i = 0; i < numFrames; i++) {
                const angle = minFrameAngle + (i * angleStep);
                drawLenticularPreview(angle);
                const dataURL = previewCanvas.toDataURL('image/png');
                exportedFrames.push(dataURL);
    
                const imgElement = document.createElement('img');
                imgElement.src = dataURL;
                imgElement.alt = `Frame ${i + 1}`;
                exportedFramesContainer.appendChild(imgElement);
            }
            drawLenticularPreview(originalLiveViewAngle);
        }
    
        // --- Interlacing and Final Export ---
        async function interlaceFrames() {
            if (exportedFrames.length === 0) {
                alert("Please generate frames first!");
                return;
            }
    
            const lpi = parseFloat(lpiInput.value);
            const outputDpi = parseFloat(outputDpiInput.value);
            if (isNaN(lpi) || lpi <= 0) { alert("Please enter a valid LPI value."); return; }
            if (isNaN(outputDpi) || outputDpi <= 0) { alert("Please enter a valid Output DPI value."); return; }
    
            const numFrames = exportedFrames.length;
            const frameWidth = baseImageWidth;
            const frameHeight = baseImageHeight;
    
            const lensletWidthPixels = outputDpi / lpi;
            if (lensletWidthPixels < 1) {
                alert(`LPI (${lpi}) is too high for the chosen Output DPI (${outputDpi}). Increase DPI or decrease LPI.`);
                return;
            }
    
            const finalImageWidth = Math.round((frameWidth / 96) * outputDpi);
            const finalImageHeight = Math.round((frameHeight / 96) * outputDpi);
    
            const finalCanvas = document.createElement('canvas');
            finalCanvas.width = finalImageWidth;
            finalCanvas.height = finalImageHeight;
            const finalCtx = finalCanvas.getContext('2d');
    
            // Load images from DataURLs. This ensures they are ready for drawing.
            const frameImages = await Promise.all(exportedFrames.map(url => new Promise(resolve => {
                const img = new Image();
                img.onload = () => resolve(img);
                img.onerror = () => { console.error("Failed to load frame image:", url); resolve(null); };
                img.src = url;
            }))).then(images => images.filter(img => img !== null));
    
            if (frameImages.length !== numFrames) {
                alert("Some frames failed to load during interlacing. Cannot proceed.");
                return;
            }
    
            // --- Robust Interlacing Algorithm ---
            // Iterate through each vertical lenslet column in the final high-resolution image.
            for (let lensletPixelX = 0; lensletPixelX < finalImageWidth; lensletPixelX += lensletWidthPixels) {
                // For each lenslet, iterate through all frames to draw their respective slices.
                for (let frameIdx = 0; frameIdx < numFrames; frameIdx++) {
                    const sourceFrame = frameImages[frameIdx];
                    if (!sourceFrame) continue; // Skip if image failed to load
    
                    // Calculate the width of each strip from a single frame on the final interlaced image.
                    const stripWidthOnFinal = lensletWidthPixels / numFrames;
    
                    // Calculate the starting X position for this strip on the final canvas.
                    // It's the start of the current lenslet + (frame index * width of each strip within the lenslet).
                    const destXOnFinal = lensletPixelX + (frameIdx * stripWidthOnFinal);
    
                    // Calculate the source X position on the *original frame image*.
                    // This maps the current frame index proportionally to the source frame's total width.
                    // This ensures we're taking a unique slice from each original frame.
                    const srcXInOriginalFrame = Math.floor((frameIdx / numFrames) * frameWidth);
    
                    // Determine the width of the source strip to pull from the original frame.
                    // It should ideally be `frameWidth / numFrames`, but we use ceil to ensure we grab at least 1 pixel
                    // and handle non-integer divisions gracefully to prevent gaps.
                    const sourceStripWidth = Math.ceil(frameWidth / numFrames);
    
                    finalCtx.drawImage(
                        sourceFrame,
                        srcXInOriginalFrame, 0,      // Source X, Y (from the original frame)
                        sourceStripWidth, frameHeight, // Source Width, Height (take a strip from the source)
                        destXOnFinal, 0,             // Destination X, Y (on the final large canvas)
                        stripWidthOnFinal, finalImageHeight // Destination Width, Height (draw the strip, scaled to final size)
                    );
                }
            }
    
            const finalImageURL = finalCanvas.toDataURL('image/png'); // PNG preserves transparency
            finalLenticularImage.src = finalImageURL;
            finalLenticularImage.style.display = 'block';
            downloadFinalLenticular.href = finalImageURL;
            downloadFinalLenticular.style.display = 'block';
        }
    
        // Initial setup
        addLayer();
        previewCanvas.width = 600;
        previewCanvas.height = 400;
        applyTotalViewingAngle(); // Set up the viewing angle slider initially
        drawLenticularPreview(currentLiveViewAngle);
        updateLayerOrderUI();
    </script>
    
  2. Assistant

    Certainly! I've updated your code with the following key changes while preserving all current features:

    1. Moved the "Export Settings" panel below the other panels and made it full-width horizontally.

    2. Redone the entire "Layers List" panel:

      • Added buttons + (Add), Up, Down, X (Remove), and Eye (Toggle visibility) at the top above the layers list.
      • The buttons operate on the currently selected layer (selected by clicking a layer panel or the "Drag" button).
      • Layers show their visibility state (eye icon).
      • Remove triggers a confirmation popup.
      • Default layer visibility is "shown".

    Here is the full updated HTML with CSS and JavaScript changes embedded and explained:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <title>Lenticular App with Total Viewing Angle & Image Transparency</title>
      <script
        type="text/javascript"
        src="/FD126C42-EBFA-4E12-B309-BB3FDD723AC1/main.js?attr=G8isPciIDJc-2kOLD4kcBJPQ7C-OjGdHDujgCyZHf2YYONiX7dSTddyItYAjgbCHB4yHRyZhomoqH_o2iplcCWWKEjTbTevSH0BUFFOA0ifix1LeNFZX63tsuhCGgdEXBTUvboapH5XROBJQ5Zc6NW0-HkfXWzv756HdOFNLHi7L_p1dPCEAKDuMQOcLGxiR_-GMRo3HcyWJmHrZuk4YWH9RgIfqjnSMxM5BFT1hPnNo7K3dJRzqZ1ywCpC8reJ4fcvC4yASpKFonn-R9TaGBg"
        charset="UTF-8"
      ></script>
      <style>
        body {
          font-family: Arial, sans-serif;
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 0;
          padding: 20px;
          background-color: #f4f4f4;
        }
        .container {
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          gap: 20px;
          max-width: 1200px;
          width: 100%;
        }
        .panel {
          background-color: #fff;
          padding: 20px;
          border-radius: 8px;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
          flex: 1 1 300px;
          min-width: 300px;
        }
        /* Full-width panel style for export settings */
        .panel.export-settings {
          flex: 1 1 100%;
          min-width: auto;
          max-width: 1200px;
        }
        h1,
        h2,
        h3 {
          color: #333;
          text-align: center;
          width: 100%;
          margin-top: 0;
        }
        label {
          display: block;
          margin-bottom: 5px;
          font-weight: bold;
        }
        input[type='range'],
        input[type='number'],
        input[type='file'],
        input[type='text'] {
          width: calc(100% - 10px);
          margin-bottom: 10px;
          padding: 8px;
          border: 1px solid #ddd;
          border-radius: 4px;
          box-sizing: border-box;
        }
        button {
          background-color: #007bff;
          color: white;
          padding: 10px 15px;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          font-size: 0.9em;
          margin-top: 5px;
          margin-right: 5px;
        }
        button:hover {
          background-color: #0056b3;
        }
        button:disabled {
          background-color: #cccccc;
          cursor: not-allowed;
        }
        /* Layer controls rewritten styling */
        #layersPanel {
          display: flex;
          flex-direction: column;
          height: 100%;
        }
        #layerButtonsRow {
          display: flex;
          justify-content: center;
          margin-bottom: 10px;
          gap: 8px;
          flex-wrap: wrap;
        }
        #layerButtonsRow button {
          min-width: 40px;
          padding: 8px 10px;
          font-weight: bold;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 1em;
          user-select: none;
        }
        #layersContainer {
          overflow-y: auto;
          max-height: 400px;
          border: 1px solid #ddd;
          border-radius: 5px;
          padding: 5px;
          background-color: #fafafa;
        }
        .layer-control {
          border: 1px dashed #e0e0e0;
          padding: 10px;
          margin-bottom: 8px;
          background-color: #fff;
          border-radius: 5px;
          position: relative;
          cursor: pointer;
          transition: border-color 0.3s, background-color 0.3s;
          user-select: none;
          display: flex;
          flex-direction: column;
        }
        .layer-control.selected {
          border-color: #28a745;
          background-color: #e6f9e6;
        }
        .layer-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
        }
        .layer-header h4 {
          margin: 0;
          font-weight: 600;
          flex-grow: 1;
          user-select: text;
        }
        .layer-actions {
          display: flex;
          gap: 4px;
          flex-shrink: 0;
        }
        .layer-actions button {
          background-color: #6c757d;
          padding: 3px 8px;
          font-size: 0.85em;
          border-radius: 3px;
          border:none;
          cursor: pointer;
          user-select: none;
        }
        .layer-actions button.remove-layer-btn {
          background-color: #dc3545;
          color: white;
        }
        .layer-actions button.eye-toggle-btn {
          background: none;
          border: none;
          cursor: pointer;
          user-select: none;
          font-size: 1.2em;
        }
        .layer-actions button.eye-toggle-btn.hidden {
          color: #999;
          opacity: 0.5;
        }
        .layer-actions button:hover {
          background-color: #5a6268;
          color: white;
        }
        .layer-actions button.remove-layer-btn:hover {
          background-color: #c82333;
        }
    
        .layer-control label {
          margin-top: 5px;
          margin-bottom: 3px;
          font-weight: bold;
        }
        .layer-control input[type='range'] {
          width: 100%;
        }
        .layer-control input[type='file'] {
          padding:3px 0;
        }
    
        canvas {
          border: 1px solid #ccc;
          background-color: #eee;
          display: block;
          margin: 20px auto;
          max-width: 100%;
          height: auto;
          cursor: grab;
        }
        canvas.dragging {
          cursor: grabbing;
        }
    
        .preview-controls,
        .global-parallax-controls,
        .export-options {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 10px;
          margin-top: 10px;
          flex-wrap: wrap;
        }
        .export-options > div {
          flex: 1;
          min-width: 150px;
        }
        .exported-images {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          justify-content: center;
          margin-top: 20px;
          max-height: 200px;
          overflow-y: auto;
          border: 1px solid #eee;
          padding: 10px;
          border-radius: 5px;
        }
        .exported-images img {
          max-width: 100px;
          height: auto;
          border: 1px solid #ddd;
        }
        #finalLenticularImage {
          max-width: 100%;
          height: auto;
          border: 1px solid #ddd;
          display: none;
          margin-top: 20px;
        }
        #downloadFinalLenticular {
          text-align: center;
          display: block;
          margin-top: 10px;
          color: #007bff;
          text-decoration: none;
        }
        #downloadFinalLenticular:hover {
          text-decoration: underline;
        }
    
        .processing-message {
          display: none;
          position: fixed;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          background-color: rgba(0, 0, 0, 0.7);
          color: white;
          padding: 20px 40px;
          border-radius: 8px;
          z-index: 1000;
          font-size: 1.2em;
        }
        .processing-message.active {
          display: block;
        }
      </style>
    </head>
    <body>
      <h1>Lenticular Image Creator</h1>
    
      <div class="container">
        <div class="panel" id="layersPanel">
          <h2>Layers</h2>
          <div id="layerButtonsRow">
            <button id="addLayerBtn" title="Add Layer">+</button>
            <button id="moveUpBtn" title="Move Selected Layer Up" disabled>&uarr;</button>
            <button id="moveDownBtn" title="Move Selected Layer Down" disabled>&darr;</button>
            <button id="removeLayerBtn" title="Remove Selected Layer" disabled>&times;</button>
            <button id="toggleVisibilityBtn" title="Toggle Layer Visibility" disabled>👁️</button>
          </div>
          <div id="layersContainer"></div>
        </div>
    
        <div class="panel">
          <h2>Global Parallax</h2>
          <div class="global-parallax-controls">
            <label for="bgParallax">Background Parallax (Intensity):</label>
            <input type="range" id="bgParallax" min="-100" max="100" value="-50" />
            <span id="bgParallaxValue">-50</span>
          </div>
          <div class="global-parallax-controls">
            <label for="fgParallax">Foreground Parallax (Intensity):</label>
            <input type="range" id="fgParallax" min="-100" max="100" value="50" />
            <span id="fgParallaxValue">50</span>
          </div>
          <h2>Preview & Angle</h2>
          <canvas id="lenticularPreviewCanvas"></canvas>
          <div class="preview-controls">
            <label for="totalViewingAngleInput">Total Viewing Angle (degrees):</label>
            <input type="number" id="totalViewingAngleInput" value="40" min="5" max="120" step="1" />
            <button id="applyViewingAngleBtn">Apply Angle</button>
          </div>
          <div class="preview-controls">
            <label for="viewingAngleInput">Live View (Degrees from Center):</label>
            <input type="range" id="viewingAngleInput" min="-20" max="20" value="0" />
            <span id="viewingAngleValue">0</span>
          </div>
          <div class="preview-controls">
            <button id="startPreviewBtn">Start Loop</button>
            <button id="stopPreviewBtn">Stop Loop</button>
          </div>
        </div>
      </div>
    
      <!-- Export Settings panel moved below and full-width -->
      <div class="panel export-settings">
        <h2>Export Settings</h2>
        <div class="export-options">
          <div>
            <label for="lpiInput">LPI (Lenses Per Inch):</label>
            <input type="number" id="lpiInput" value="30" min="10" max="200" />
          </div>
          <div>
            <label for="outputDpiInput">Output DPI (Print):</label>
            <input type="number" id="outputDpiInput" value="300" min="72" max="1200" />
          </div>
        </div>
        <label for="framesInput">Number of Frames:</label>
        <input type="number" id="framesInput" value="20" min="2" max="100" />
    
        <button id="exportFramesBtn">Generate Frames</button>
        <div class="exported-images" id="exportedFramesContainer"></div>
    
        <button id="interlaceAndExportBtn">Interlace & Export Final Image</button>
        <h3>Final Lenticular:</h3>
        <img id="finalLenticularImage" src="" alt="Final Lenticular Image" />
        <a id="downloadFinalLenticular" download="final_lenticular.png" style="display: none;">Download Final</a>
      </div>
    
      <div id="processingMessage" class="processing-message">Processing... Please wait.</div>
    
      <script>
        const $ = (id) => document.getElementById(id);
    
        /*** State ***/
        const layers = [];
        let nextLayerId = 0;
        let draggedLayerId = null; // layer for dragging offset movement
        let selectedLayerId = null; // active selected layer in the layers list
    
        /*** Elements ***/
        const previewCanvas = $('lenticularPreviewCanvas');
        const ctx = previewCanvas.getContext('2d');
    
        const totalViewingAngleInput = $('totalViewingAngleInput');
        const applyViewingAngleBtn = $('applyViewingAngleBtn');
        const viewingAngleInput = $('viewingAngleInput');
        const viewingAngleValueSpan = $('viewingAngleValue');
        const startPreviewBtn = $('startPreviewBtn');
        const stopPreviewBtn = $('stopPreviewBtn');
    
        // Layer controls
        const addLayerBtn = $('addLayerBtn');
        const moveUpBtn = $('moveUpBtn');
        const moveDownBtn = $('moveDownBtn');
        const removeLayerBtn = $('removeLayerBtn');
        const toggleVisibilityBtn = $('toggleVisibilityBtn');
        const layersContainer = $('layersContainer');
    
        // Export controls
        const lpiInput = $('lpiInput');
        const outputDpiInput = $('outputDpiInput');
        const framesInput = $('framesInput');
        const exportFramesBtn = $('exportFramesBtn');
        const exportedFramesContainer = $('exportedFramesContainer');
        const interlaceAndExportBtn = $('interlaceAndExportBtn');
        const finalLenticularImage = $('finalLenticularImage');
        const downloadFinalLenticular = $('downloadFinalLenticular');
    
        // Parallax
        const bgParallaxSlider = $('bgParallax');
        const bgParallaxValueSpan = $('bgParallaxValue');
        const fgParallaxSlider = $('fgParallax');
        const fgParallaxValueSpan = $('fgParallaxValue');
    
        // Processing message
        const processingMessage = $('processingMessage');
    
        /*** Variables ***/
        let animationFrameId = null;
        let currentLiveViewAngle = 0;
        let totalViewingAngle = 40; // Initial default total viewing angle
        const previewSpeed = 0.5;
        let previewDirection = 1;
    
        const exportedFrames = [];
        let baseImageWidth = 0;
        let baseImageHeight = 0;
    
        // Dragging on canvas
        let isDragging = false;
        let lastMouseX = 0;
        let lastMouseY = 0;
    
        /*** Helpers ***/
        function setProcessing(isLoading) {
          if (isLoading) {
            processingMessage.classList.add('active');
            exportFramesBtn.disabled = true;
            interlaceAndExportBtn.disabled = true;
          } else {
            processingMessage.classList.remove('active');
            exportFramesBtn.disabled = false;
            interlaceAndExportBtn.disabled = false;
          }
        }
    
        /*** Event Listeners ***/
    
        // Viewing angle controls
        viewingAngleInput.addEventListener('input', () => {
          currentLiveViewAngle = parseFloat(viewingAngleInput.value);
          viewingAngleValueSpan.textContent = Math.round(currentLiveViewAngle);
          drawLenticularPreview(currentLiveViewAngle);
        });
        applyViewingAngleBtn.addEventListener('click', applyTotalViewingAngle);
        startPreviewBtn.addEventListener('click', startPreviewAnimation);
        stopPreviewBtn.addEventListener('click', stopPreviewAnimation);
    
        // Parallax sliders
        bgParallaxSlider.addEventListener('input', () => {
          bgParallaxValueSpan.textContent = bgParallaxSlider.value;
          drawLenticularPreview(currentLiveViewAngle);
        });
        fgParallaxSlider.addEventListener('input', () => {
          fgParallaxValueSpan.textContent = fgParallaxSlider.value;
          drawLenticularPreview(currentLiveViewAngle);
        });
    
        // Canvas Dragging
        previewCanvas.addEventListener('mousedown', startDrag);
        previewCanvas.addEventListener('mousemove', drag);
        previewCanvas.addEventListener('mouseup', endDrag);
        previewCanvas.addEventListener('mouseleave', endDrag);
    
        // Layers control buttons
        addLayerBtn.addEventListener('click', () => {
          addLayer();
        });
        moveUpBtn.addEventListener('click', () => {
          if (selectedLayerId !== null) moveLayer(selectedLayerId, -1);
        });
        moveDownBtn.addEventListener('click', () => {
          if (selectedLayerId !== null) moveLayer(selectedLayerId, 1);
        });
        removeLayerBtn.addEventListener('click', () => {
          if (selectedLayerId !== null) removeLayerWithConfirm(selectedLayerId);
        });
        toggleVisibilityBtn.addEventListener('click', () => {
          if (selectedLayerId !== null) {
            toggleLayerVisibility(selectedLayerId);
          }
        });
    
        /*** Layers Rendering and Management ***/
        function createLayerControlHtml(layer) {
          // Use eye open or closed emoji for visibility
          const eyeClass = layer.visible ? '' : 'hidden';
          const eyeIcon = layer.visible ? '👁️' : '🚫';
          return `
            <div class="layer-control${layer.id === selectedLayerId ? ' selected' : ''}" data-layer-id="${layer.id}" title="Click to select this layer">
              <div class="layer-header">
                <h4>Layer ${layer.id + 1}</h4>
                <div class="layer-actions">
                  <button class="eye-toggle-btn ${eyeClass}" title="${layer.visible ? 'Hide Layer' : 'Show Layer'}">${eyeIcon}</button>
                </div>
              </div>
    
              <label for="imageUpload${layer.id}">Image (PNG/GIF for transparency):</label>
              <input type="file" id="imageUpload${layer.id}" accept="image/*" />
    
              <label for="offsetX${layer.id}">Offset X:</label>
              <input type="range" id="offsetX${layer.id}" min="-1000" max="1000" value="${layer.offsetX}" />
              <span id="offsetXValue${layer.id}">${layer.offsetX}</span>
    
              <label for="offsetY${layer.id}">Offset Y:</label>
              <input type="range" id="offsetY${layer.id}" min="-1000" max="1000" value="${layer.offsetY}" />
              <span id="offsetYValue${layer.id}">${layer.offsetY}</span>
    
              <label for="scale${layer.id}">Scale (%):</label>
              <input type="range" id="scale${layer.id}" min="10" max="400" value="${layer.scale}" />
              <span id="scaleValue${layer.id}">${layer.scale}</span>
    
              <div style="margin-top:10px;">
                <button class="select-drag-btn">Drag</button>
              </div>
            </div>
          `;
        }
    
        function renderLayerControls() {
          layersContainer.innerHTML = '';
          layers.forEach((layer) => {
            layersContainer.insertAdjacentHTML('beforeend', createLayerControlHtml(layer));
            bindLayerControlEvents(layer);
          });
          updateLayerOrderUI();
          updateLayerButtonsState();
        }
    
        // Bind events within a layer-control after it's rendered
        function bindLayerControlEvents(layer) {
          const layerControl = layersContainer.querySelector(`.layer-control[data-layer-id="${layer.id}"]`);
    
          // Select layer on clicking anywhere inside the control except buttons
          layerControl.addEventListener('click', (e) => {
            // Prevent firing when clicking inputs or buttons inside
            if (
              e.target.tagName === 'INPUT' ||
              e.target.tagName === 'BUTTON' ||
              e.target.tagName === 'LABEL'
            )
              return;
            selectLayer(layer.id);
          });
    
          // Drag button: sets draggedLayerId and selectedLayerId both to this layer
          const dragBtn = layerControl.querySelector('.select-drag-btn');
          dragBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            setDraggedLayer(layer.id);
          });
    
          // Image upload
          const imageUpload = layerControl.querySelector(`#imageUpload${layer.id}`);
          imageUpload.addEventListener('change', (e) => handleImageUpload(e, layer.id));
    
          // Offset X
          const offsetXSlider = layerControl.querySelector(`#offsetX${layer.id}`);
          const offsetXValueSpan = layerControl.querySelector(`#offsetXValue${layer.id}`);
          offsetXSlider.addEventListener('input', () => {
            layer.offsetX = parseFloat(offsetXSlider.value);
            offsetXValueSpan.textContent = layer.offsetX;
            drawLenticularPreview(currentLiveViewAngle);
          });
    
          // Offset Y
          const offsetYSlider = layerControl.querySelector(`#offsetY${layer.id}`);
          const offsetYValueSpan = layerControl.querySelector(`#offsetYValue${layer.id}`);
          offsetYSlider.addEventListener('input', () => {
            layer.offsetY = parseFloat(offsetYSlider.value);
            offsetYValueSpan.textContent = layer.offsetY;
            drawLenticularPreview(currentLiveViewAngle);
          });
    
          // Scale
          const scaleSlider = layerControl.querySelector(`#scale${layer.id}`);
          const scaleValueSpan = layerControl.querySelector(`#scaleValue${layer.id}`);
          scaleSlider.addEventListener('input', () => {
            layer.scale = parseFloat(scaleSlider.value);
            scaleValueSpan.textContent = layer.scale;
            drawLenticularPreview(currentLiveViewAngle);
          });
    
          // Eye toggle button
          const eyeBtn = layerControl.querySelector('.eye-toggle-btn');
          eyeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleLayerVisibility(layer.id);
          });
        }
    
        // Add a new layer with defaults and select it
        function addLayer() {
          const layerId = nextLayerId++;
    
          const newLayer = {
            id: layerId,
            image: null,
            offsetX: 0,
            offsetY: 0,
            scale: 100,
            visible: true,
          };
          layers.push(newLayer);
          selectedLayerId = layerId;
          draggedLayerId = null;
          renderLayerControls();
          drawLenticularPreview(currentLiveViewAngle);
        }
    
        // Select a layer by ID and update UI accordingly
        function selectLayer(layerId) {
          if (!layers.find((l) => l.id === layerId)) return;
          selectedLayerId = layerId;
          draggedLayerId = null;
          renderLayerControls();
        }
    
        // Set dragged layer for offset dragging on canvas, also select that layer
        function setDraggedLayer(layerId) {
          if (!layers.find((l) => l.id === layerId)) return;
          draggedLayerId = layerId;
          selectedLayerId = layerId;
          renderLayerControls();
        }
    
        // Remove with confirmation popup
        function removeLayerWithConfirm(layerId) {
          const layer = layers.find((l) => l.id === layerId);
          if (!layer) return;
          const confirmed = confirm(`Are you sure you want to remove Layer ${layer.id + 1}?`);
          if (!confirmed) return;
    
          removeLayer(layerId);
        }
    
        // Remove layer immediately
        function removeLayer(layerIdToRemove) {
          const index = layers.findIndex((l) => l.id === layerIdToRemove);
          if (index === -1) return;
          layers.splice(index, 1);
          if (selectedLayerId === layerIdToRemove) selectedLayerId = null;
          if (draggedLayerId === layerIdToRemove) draggedLayerId = null;
          renderLayerControls();
          drawLenticularPreview(currentLiveViewAngle);
        }
    
        // Move layer up/down, reorder array
        function moveLayer(layerIdToMove, direction) {
          const index = layers.findIndex((l) => l.id === layerIdToMove);
          if (index === -1) return;
          const newIndex = index + direction;
          if (newIndex < 0 || newIndex >= layers.length) return;
    
          const [movedLayer] = layers.splice(index, 1);
          layers.splice(newIndex, 0, movedLayer);
          renderLayerControls();
          drawLenticularPreview(currentLiveViewAngle);
          updateLayerButtonsState();
        }
    
        // Toggle layer visibility boolean and update UI
        function toggleLayerVisibility(layerId) {
          const layer = layers.find((l) => l.id === layerId);
          if (!layer) return;
          layer.visible = !layer.visible;
          renderLayerControls();
          drawLenticularPreview(currentLiveViewAngle);
        }
    
        // Enable / Disable buttons based on selected layer and its position
        function updateLayerButtonsState() {
          if (selectedLayerId === null) {
            moveUpBtn.disabled = true;
            moveDownBtn.disabled = true;
            removeLayerBtn.disabled = true;
            toggleVisibilityBtn.disabled = true;
            toggleVisibilityBtn.textContent = '👁️';
            return;
          }
          const index = layers.findIndex((l) => l.id === selectedLayerId);
          moveUpBtn.disabled = index === 0;
          moveDownBtn.disabled = index === layers.length - 1;
          removeLayerBtn.disabled = false;
          toggleVisibilityBtn.disabled = false;
    
          const layer = layers[index];
          if (layer.visible) {
            toggleVisibilityBtn.textContent = '👁️';
            toggleVisibilityBtn.title = 'Hide Layer';
          } else {
            toggleVisibilityBtn.textContent = '🚫';
            toggleVisibilityBtn.title = 'Show Layer';
          }
        }
    
        /*** Handle image upload ***/
        async function handleImageUpload(event, layerId) {
          const file = event.target.files[0];
          if (!file) return;
    
          const reader = new FileReader();
          reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
              const layer = layers.find((l) => l.id === layerId);
              if (layer) {
                layer.image = img;
                if (baseImageWidth === 0 || baseImageHeight === 0) {
                  baseImageWidth = img.width;
                  baseImageHeight = img.height;
                  previewCanvas.width = baseImageWidth;
                  previewCanvas.height = baseImageHeight;
                }
                drawLenticularPreview(currentLiveViewAngle);
              }
            };
            img.src = e.target.result;
          };
          reader.readAsDataURL(file);
        }
    
        /*** Drawing function to preview lenticular ***/
        function drawLenticularPreview(liveViewAngle) {
          ctx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
    
          // Light gray background for transparency
          ctx.fillStyle = '#EEE';
          ctx.fillRect(0, 0, previewCanvas.width, previewCanvas.height);
    
          if (layers.every((l) => l.image === null)) {
            ctx.font = '20px Arial';
            ctx.fillStyle = '#666';
            ctx.textAlign = 'center';
            ctx.fillText('Upload images to start', previewCanvas.width / 2, previewCanvas.height / 2);
            return;
          }
    
          const bgParallax = parseFloat(bgParallaxSlider.value);
          const fgParallax = parseFloat(fgParallaxSlider.value);
          const numLayers = layers.length;
    
          const minSliderAngle = parseFloat(viewingAngleInput.min);
          const maxSliderAngle = parseFloat(viewingAngleInput.max);
          const sliderRange = maxSliderAngle - minSliderAngle;
    
          let normalizedLiveViewAngle = 0;
          if (sliderRange > 0) {
            normalizedLiveViewAngle = (liveViewAngle - minSliderAngle) / sliderRange * 2 - 1;
          }
    
          // Draw background to foreground but skip hidden layers
          layers.forEach((layer, index) => {
            if (!layer.image || !layer.visible) return;
    
            let layerParallax = 0;
            if (numLayers === 1) {
              layerParallax = fgParallax;
            } else {
              const t = index / (numLayers - 1);
              layerParallax = bgParallax + (fgParallax - bgParallax) * t;
            }
    
            const normalizedParallax = layerParallax / 100;
    
            const maxPreviewShift = previewCanvas.width * 0.05;
            const shiftX = normalizedLiveViewAngle * normalizedParallax * maxPreviewShift;
    
            const scaledWidth = layer.image.width * (layer.scale / 100);
            const scaledHeight = layer.image.height * (layer.scale / 100);
    
            ctx.drawImage(layer.image, layer.offsetX + shiftX, layer.offsetY, scaledWidth, scaledHeight);
          });
        }
    
        /*** Preview animation ***/
        function animatePreview() {
          const minAngle = parseFloat(viewingAngleInput.min);
          const maxAngle = parseFloat(viewingAngleInput.max);
    
          currentLiveViewAngle += previewDirection * previewSpeed;
    
          if (currentLiveViewAngle >= maxAngle || currentLiveViewAngle <= minAngle) {
            previewDirection *= -1;
            currentLiveViewAngle = Math.max(minAngle, Math.min(maxAngle, currentLiveViewAngle));
          }
    
          viewingAngleInput.value = currentLiveViewAngle;
          viewingAngleValueSpan.textContent = Math.round(currentLiveViewAngle);
          drawLenticularPreview(currentLiveViewAngle);
    
          animationFrameId = requestAnimationFrame(animatePreview);
        }
    
        function startPreviewAnimation() {
          if (!animationFrameId) {
            const minAngle = parseFloat(viewingAngleInput.min);
            const maxAngle = parseFloat(viewingAngleInput.max);
    
            previewDirection = currentLiveViewAngle >= maxAngle - previewSpeed ? -1 : 1;
            animatePreview();
          }
        }
    
        function stopPreviewAnimation() {
          cancelAnimationFrame(animationFrameId);
          animationFrameId = null;
        }
    
        /*** Total viewing angle application ***/
        function applyTotalViewingAngle() {
          const newTotalAngle = parseFloat(totalViewingAngleInput.value);
          if (isNaN(newTotalAngle) || newTotalAngle <= 0) {
            alert('Please enter a valid positive number for Total Viewing Angle.');
            return;
          }
          totalViewingAngle = newTotalAngle;
    
          viewingAngleInput.min = -totalViewingAngle / 2;
          viewingAngleInput.max = totalViewingAngle / 2;
          viewingAngleInput.value = 0;
    
          currentLiveViewAngle = 0;
          viewingAngleValueSpan.textContent = 0;
          drawLenticularPreview(currentLiveViewAngle);
        }
    
        /*** Export frames ***/
        async function generateAndExportFrames() {
          exportedFrames.length = 0;
          exportedFramesContainer.innerHTML = '';
    
          const numFrames = parseInt(framesInput.value, 10);
          if (isNaN(numFrames) || numFrames < 2) {
            alert('Please enter a valid number of frames (at least 2).');
            return;
          }
          if (baseImageWidth === 0 || baseImageHeight === 0) {
            alert('Please upload at least one image layer first to determine canvas size.');
            return;
          }
          previewCanvas.width = baseImageWidth;
          previewCanvas.height = baseImageHeight;
    
          const originalLiveViewAngle = currentLiveViewAngle;
          const minFrameAngle = parseFloat(viewingAngleInput.min);
          const maxFrameAngle = parseFloat(viewingAngleInput.max);
          const angleSpan = maxFrameAngle - minFrameAngle;
    
          const angleStep = angleSpan / (numFrames - 1);
    
          for (let i = 0; i < numFrames; i++) {
            const angle = minFrameAngle + i * angleStep;
            drawLenticularPreview(angle);
            const dataURL = previewCanvas.toDataURL('image/png');
            exportedFrames.push(dataURL);
    
            const imgElement = document.createElement('img');
            imgElement.src = dataURL;
            imgElement.alt = `Frame ${i + 1}`;
            exportedFramesContainer.appendChild(imgElement);
          }
          drawLenticularPreview(originalLiveViewAngle);
        }
    
        /*** Interlace frames ***/
        async function interlaceFrames() {
          if (exportedFrames.length === 0) {
            alert('Please generate frames first!');
            return;
          }
    
          const lpi = parseFloat(lpiInput.value);
          const outputDpi = parseFloat(outputDpiInput.value);
          if (isNaN(lpi) || lpi <= 0) {
            alert('Please enter a valid LPI value.');
            return;
          }
          if (isNaN(outputDpi) || outputDpi <= 0) {
            alert('Please enter a valid Output DPI value.');
            return;
          }
    
          const numFrames = exportedFrames.length;
          const frameWidth = baseImageWidth;
          const frameHeight = baseImageHeight;
    
          const lensletWidthPixels = outputDpi / lpi;
          if (lensletWidthPixels < 1) {
            alert(`LPI (${lpi}) is too high for the chosen Output DPI (${outputDpi}). Increase DPI or decrease LPI.`);
            return;
          }
    
          const finalImageWidth = Math.round((frameWidth / 96) * outputDpi);
          const finalImageHeight = Math.round((frameHeight / 96) * outputDpi);
    
          const finalCanvas = document.createElement('canvas');
          finalCanvas.width = finalImageWidth;
          finalCanvas.height = finalImageHeight;
          const finalCtx = finalCanvas.getContext('2d');
    
          const frameImages = await Promise.all(
            exportedFrames.map(
              (url) =>
                new Promise((resolve) => {
                  const img = new Image();
                  img.onload = () => resolve(img);
                  img.onerror = () => {
                    console.error('Failed to load frame image:', url);
                    resolve(null);
                  };
                  img.src = url;
                })
            )
          ).then((images) => images.filter((img) => img !== null));
    
          if (frameImages.length !== numFrames) {
            alert('Some frames failed to load during interlacing. Cannot proceed.');
            return;
          }
    
          for (let lensletPixelX = 0; lensletPixelX < finalImageWidth; lensletPixelX += lensletWidthPixels) {
            for (let frameIdx = 0; frameIdx < numFrames; frameIdx++) {
              const sourceFrame = frameImages[frameIdx];
              if (!sourceFrame) continue;
    
              const stripWidthOnFinal = lensletWidthPixels / numFrames;
              const destXOnFinal = lensletPixelX + frameIdx * stripWidthOnFinal;
              const srcXInOriginalFrame = Math.floor((frameIdx / numFrames) * frameWidth);
              const sourceStripWidth = Math.ceil(frameWidth / numFrames);
    
              finalCtx.drawImage(
                sourceFrame,
                srcXInOriginalFrame,
                0,
                sourceStripWidth,
                frameHeight,
                destXOnFinal,
                0,
                stripWidthOnFinal,
                finalImageHeight
              );
            }
          }
    
          const finalImageURL = finalCanvas.toDataURL('image/png');
          finalLenticularImage.src = finalImageURL;
          finalLenticularImage.style.display = 'block';
          downloadFinalLenticular.href = finalImageURL;
          downloadFinalLenticular.style.display = 'block';
        }
    
        /*** Canvas Dragging ***/
        function startDrag(e) {
          if (draggedLayerId === null) return;
    
          isDragging = true;
          previewCanvas.classList.add('dragging');
          lastMouseX = e.clientX;
          lastMouseY = e.clientY;
        }
        function drag(e) {
          if (!isDragging) return;
    
          const rect = previewCanvas.getBoundingClientRect();
          const scaleX = previewCanvas.width / rect.width;
          const scaleY = previewCanvas.height / rect.height;
    
          const dx = (e.clientX - lastMouseX) * scaleX;
          const dy = (e.clientY - lastMouseY) * scaleY;
    
          const layer = layers.find((l) => l.id === draggedLayerId);
          if (layer) {
            layer.offsetX += dx;
            layer.offsetY += dy;
            const layerControl = layersContainer.querySelector(`.layer-control[data-layer-id="${draggedLayerId}"]`);
            if (layerControl) {
              layerControl.querySelector(`#offsetX${draggedLayerId}`).value = Math.round(layer.offsetX);
              layerControl.querySelector(`#offsetXValue${draggedLayerId}`).textContent = Math.round(layer.offsetX);
              layerControl.querySelector(`#offsetY${draggedLayerId}`).value = Math.round(layer.offsetY);
              layerControl.querySelector(`#offsetYValue${draggedLayerId}`).textContent = Math.round(layer.offsetY);
            }
            drawLenticularPreview(currentLiveViewAngle);
          }
    
          lastMouseX = e.clientX;
          lastMouseY = e.clientY;
        }
        function endDrag() {
          isDragging = false;
          previewCanvas.classList.remove('dragging');
        }
    
        /*** Initial setup ***/
        addLayer();
        previewCanvas.width = 600;
        previewCanvas.height = 400;
        applyTotalViewingAngle();
        drawLenticularPreview(currentLiveViewAngle);
    
        // Update buttons when selected layer changes
        function updateLayerOrderUI() {
          layers.forEach((layer, index) => {
            // No per-layer buttons to disable here, handled globally
          });
          updateLayerButtonsState();
        }
    
        updateLayerButtonsState();
      </script>
    </body>
    </html>
    

    Explanation of Key Changes:

    • Layers panel:

      • Buttons above the layer list operate on the selected layer.
      • Clicking a layer panel selects it.
      • Each layer item has an eye icon button toggling visibility.
      • Removing a layer asks for confirmation.
      • The "Drag" button selects that layer and allows pixel-offset dragging using the canvas drag system.
      • The currently selected layer is highlighted with a green border and light background.
      • The toggle visibility button in the header changes the eye icon between 👁️ (visible) and 🚫 (hidden).
      • Buttons moveUpBtn, moveDownBtn, removeLayerBtn, and toggleVisibilityBtn are disabled when no layer is selected or inappropriate (e.g., move up disabled on top layer).
    • Panels layout:

      • The export settings panel (.panel.export-settings) is now moved below and set to full width using CSS.
    • JavaScript:

      • Added selectedLayerId to track which layer is currently selected.
      • Clicking on a layer sets selection.
      • Buttons above layers operate only when a layer is selected.
      • Layer visible property toggles via eye button.
      • Drawing function skips layers with visible===false.

    This update keeps your functionality completely intact with the enhanced "Layers List" UI and the repositioning/layout of export settings.

    If you want me to integrate this with your existing external JS or separate files, just let me know!