To add the "Export .uv1 file" and "Load .uv1 file" functionality to your application, we'll need to make the following modifications:
- Add "Export .uv1 file" and "Load .uv1 file" buttons to the toolbar.
- Implement the export functionality to generate a .uv1 file with the specified format.
- Implement the import functionality to read a .uv1 file and update the selections accordingly.
Below is the modified code with comments explaining each change:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Box Packaging Design Selector</title>
<style>
/* ... (existing styles remain unchanged) ... */
</style>
</head>
<body>
<div id="toolbar">
<button id="importImageButton">Import Image</button>
<input type="file" id="imageLoader" accept="image/*" style="display:none"/>
<!-- Add Load and Export buttons -->
<button id="loadUVButton">Load .uv1 File</button>
<input type="file" id="uvLoader" accept=".uv1" style="display:none"/>
<button id="exportUVButton">Export .uv1 File</button>
<div id="faceList">
<!-- Faces will be dynamically added here -->
</div>
</div>
<div id="canvasContainer">
<canvas id="imageCanvas"></canvas>
</div>
<script>
// JavaScript code
// Get references to DOM elements
const importImageButton = document.getElementById('importImageButton');
const imageLoader = document.getElementById('imageLoader');
const canvas = document.getElementById('imageCanvas');
const faceList = document.getElementById('faceList');
const canvasContainer = document.getElementById('canvasContainer');
const ctx = canvas.getContext('2d');
// Add references to new buttons
const exportUVButton = document.getElementById('exportUVButton');
const loadUVButton = document.getElementById('loadUVButton');
const uvLoader = document.getElementById('uvLoader');
// Variables for canvas manipulation
let image = new Image();
let imgScale = 1;
let imgPos = { x: 0, y: 0 };
let isPanning = false;
let panStart = { x: 0, y: 0 };
let mouseStart = { x: 0, y: 0 };
// Variables for selection
let faces = ['front', 'back', 'right', 'left', 'top', 'bottom'];
let selections = {};
let currentFace = null;
let isDrawing = false;
let isEditing = false;
let editHandle = null;
let hoverHandle = null;
let handles = [];
const handleSize = 10;
// Initialize canvas size
function resizeCanvas() {
canvas.width = canvasContainer.clientWidth;
canvas.height = canvasContainer.clientHeight;
draw();
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Import image button click
importImageButton.addEventListener('click', () => {
imageLoader.click();
});
// Load selected image
imageLoader.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
image.src = event.target.result;
image.onload = () => {
imgScale = 1;
imgPos = { x: (canvas.width - image.width) / 2, y: (canvas.height - image.height) / 2 };
draw();
};
};
reader.readAsDataURL(file);
});
// Set up faces list
faces.forEach(faceName => {
// Create face item
const faceItem = document.createElement('div');
faceItem.className = 'face-item';
// Add elements to face item
const faceLabel = document.createElement('span');
faceLabel.textContent = faceName;
faceLabel.className = 'face-label';
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.disabled = false;
const deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.disabled = true;
const editButton = document.createElement('button');
editButton.textContent = 'Edit';
editButton.disabled = true;
faceItem.appendChild(faceLabel);
faceItem.appendChild(addButton);
faceItem.appendChild(deleteButton);
faceItem.appendChild(editButton);
faceList.appendChild(faceItem);
// Event listeners for buttons
addButton.addEventListener('click', () => {
currentFace = faceName;
isDrawing = true;
addButton.disabled = true;
deleteButton.disabled = false;
editButton.disabled = true; // Disable edit during drawing
// Deselect other faces
isEditing = false;
updateEditButtons();
});
deleteButton.addEventListener('click', () => {
delete selections[faceName];
addButton.disabled = false;
deleteButton.disabled = true;
editButton.disabled = true;
if (currentFace === faceName) {
currentFace = null;
isEditing = false;
}
draw();
});
editButton.addEventListener('click', () => {
if (currentFace !== faceName) {
currentFace = faceName;
isEditing = true;
updateEditButtons();
} else {
isEditing = !isEditing;
editButton.textContent = isEditing ? 'Done' : 'Edit';
}
draw();
});
function updateEditButtons() {
// Update all edit buttons based on currentFace and isEditing
const faceItems = faceList.getElementsByClassName('face-item');
Array.from(faceItems).forEach(item => {
const faceNameLabel = item.querySelector('.face-label').textContent;
const editBtn = item.querySelector('button:nth-child(4)');
if (faceNameLabel === currentFace && isEditing) {
editBtn.textContent = 'Done';
editBtn.disabled = false;
} else if (selections[faceNameLabel]) {
editBtn.textContent = 'Edit';
editBtn.disabled = false;
} else {
editBtn.textContent = 'Edit';
editBtn.disabled = true;
}
});
}
});
// Canvas event handlers
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
const mouseX = (e.clientX - rect.left);
const mouseY = (e.clientY - rect.top);
const imgMouseX = (mouseX - imgPos.x) / imgScale;
const imgMouseY = (mouseY - imgPos.y) / imgScale;
if (e.button === 1 || (e.button === 0 && e.ctrlKey)) {
// Middle mouse button or Ctrl + Left Click for panning
isPanning = true;
panStart = { x: imgPos.x, y: imgPos.y };
mouseStart = { x: e.clientX, y: e.clientY };
} else if (isDrawing && currentFace) {
// Start drawing selection rectangle
selections[currentFace] = {
x: imgMouseX,
y: imgMouseY,
width: 0,
height: 0
};
isDrawing = true;
} else if (isEditing && selections[currentFace]) {
// Check if clicked on handle
const handle = getHandleUnderMouse(mouseX, mouseY);
if (handle) {
editHandle = handle;
} else if (isInsideSelection(mouseX, mouseY, selections[currentFace])) {
// Start moving the selection
editHandle = 'move';
panStart = { x: selections[currentFace].x, y: selections[currentFace].y };
mouseStart = { x: imgMouseX, y: imgMouseY };
} else {
// Clicked outside selection, stop editing
isEditing = false;
currentFace = null;
updateEditButtons();
draw();
}
}
});
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
const mouseX = (e.clientX - rect.left);
const mouseY = (e.clientY - rect.top);
const imgMouseX = (mouseX - imgPos.x) / imgScale;
const imgMouseY = (mouseY - imgPos.y) / imgScale;
if (isPanning) {
// Panning
imgPos.x = panStart.x + (e.clientX - mouseStart.x);
imgPos.y = panStart.y + (e.clientY - mouseStart.y);
draw();
} else if (isDrawing && selections[currentFace]) {
// Update selection rectangle size
const sel = selections[currentFace];
sel.width = imgMouseX - sel.x;
sel.height = imgMouseY - sel.y;
draw();
} else if (isEditing && editHandle && selections[currentFace]) {
// Edit selection rectangle
const sel = selections[currentFace];
if (editHandle === 'move') {
sel.x = panStart.x + (imgMouseX - mouseStart.x);
sel.y = panStart.y + (imgMouseY - mouseStart.y);
} else {
// Adjust selection based on handle
adjustSelection(sel, editHandle, imgMouseX, imgMouseY);
}
draw();
} else {
// Update hover state for handles
if (isEditing && selections[currentFace]) {
hoverHandle = getHandleUnderMouse(mouseX, mouseY);
canvas.style.cursor = hoverHandle ? 'pointer' : 'default';
} else {
canvas.style.cursor = 'default';
}
}
});
canvas.addEventListener('mouseup', (e) => {
isPanning = false;
isDrawing = false;
editHandle = null;
});
canvas.addEventListener('wheel', (e) => {
// Zooming
e.preventDefault();
const delta = e.deltaY < 0 ? 1.1 : 0.9;
const rect = canvas.getBoundingClientRect();
const mouseX = (e.clientX - rect.left);
const mouseY = (e.clientY - rect.top);
const imgMouseX = (mouseX - imgPos.x) / imgScale;
const imgMouseY = (mouseY - imgPos.y) / imgScale;
imgScale *= delta;
imgPos.x = mouseX - imgMouseX * imgScale;
imgPos.y = mouseY - imgMouseY * imgScale;
draw();
});
canvas.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
function draw() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw image
if (image.src) {
ctx.drawImage(image, imgPos.x, imgPos.y, image.width * imgScale, image.height * imgScale);
}
// Draw selections
for (const faceName in selections) {
const sel = selections[faceName];
const isCurrent = faceName === currentFace;
drawSelection(sel, faceName, isCurrent && isEditing);
}
}
function drawSelection(sel, label, showHandles) {
ctx.save();
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.strokeRect(
sel.x * imgScale + imgPos.x,
sel.y * imgScale + imgPos.y,
sel.width * imgScale,
sel.height * imgScale
);
// Draw label
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
ctx.font = 'bold 14px Arial';
const textWidth = ctx.measureText(label).width;
ctx.fillRect(
(sel.x + sel.width / 2) * imgScale + imgPos.x - textWidth / 2 - 5,
(sel.y + sel.height / 2) * imgScale + imgPos.y - 15,
textWidth + 10,
20
);
ctx.fillStyle = 'black';
ctx.fillText(
label,
(sel.x + sel.width / 2) * imgScale + imgPos.x - textWidth / 2,
(sel.y + sel.height / 2) * imgScale + imgPos.y
);
// Draw handles if editing
if (showHandles) {
updateHandles(sel);
handles.forEach(handle => {
ctx.fillStyle = 'red';
ctx.fillRect(handle.x - handleSize / 2, handle.y - handleSize / 2, handleSize, handleSize);
});
}
ctx.restore();
}
function updateHandles(sel) {
handles = [];
const points = [
{ x: sel.x, y: sel.y }, // Top-left
{ x: sel.x + sel.width, y: sel.y }, // Top-right
{ x: sel.x, y: sel.y + sel.height }, // Bottom-left
{ x: sel.x + sel.width, y: sel.y + sel.height } // Bottom-right
];
points.forEach((pt, idx) => {
handles.push({
x: pt.x * imgScale + imgPos.x,
y: pt.y * imgScale + imgPos.y,
pos: ['nw', 'ne', 'sw', 'se'][idx]
});
});
}
function getHandleUnderMouse(mouseX, mouseY) {
return handles.find(handle => {
return (
mouseX >= handle.x - handleSize / 2 &&
mouseX <= handle.x + handleSize / 2 &&
mouseY >= handle.y - handleSize / 2 &&
mouseY <= handle.y + handleSize / 2
);
})?.pos;
}
function adjustSelection(sel, handlePos, imgMouseX, imgMouseY) {
switch (handlePos) {
case 'nw':
sel.width += sel.x - imgMouseX;
sel.height += sel.y - imgMouseY;
sel.x = imgMouseX;
sel.y = imgMouseY;
break;
case 'ne':
sel.width = imgMouseX - sel.x;
sel.height += sel.y - imgMouseY;
sel.y = imgMouseY;
break;
case 'sw':
sel.width += sel.x - imgMouseX;
sel.x = imgMouseX;
sel.height = imgMouseY - sel.y;
break;
case 'se':
sel.width = imgMouseX - sel.x;
sel.height = imgMouseY - sel.y;
break;
}
// Prevent negative width and height
if (sel.width < 0) {
sel.x += sel.width;
sel.width *= -1;
}
if (sel.height < 0) {
sel.y += sel.height;
sel.height *= -1;
}
}
// Helper function to check if point is inside selection rectangle
function isInsideSelection(mouseX, mouseY, sel) {
const x = sel.x * imgScale + imgPos.x;
const y = sel.y * imgScale + imgPos.y;
const width = sel.width * imgScale;
const height = sel.height * imgScale;
return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height;
}
// ------------------------------
// Export and Load functionality
// ------------------------------
// Event listener for Export button
exportUVButton.addEventListener('click', () => {
if (!image.src) {
alert('Please import an image first.');
return;
}
// Ensure all faces have selections
// if (Object.keys(selections).length !== faces.length) {
// alert('Please select all faces before exporting.');
// return;
// }
// Generate UV1 file content
const lines = [];
// First line: Image size
lines.push(`size,${image.width},${image.height}`);
// Next lines: Face data
faces.forEach(faceName => {
const sel = selections[faceName];
if (sel) {
// Format: face_name, x, y, width, height
// Round to 3 decimal places
const x = sel.x.toFixed(3);
const y = sel.y.toFixed(3);
const width = sel.width.toFixed(3);
const height = sel.height.toFixed(3);
lines.push(`${faceName},${x},${y},${width},${height}`);
} else {
// If face is not selected, output placeholder
lines.push(`${faceName},0,0,0,0`);
}
});
const uvContent = lines.join('\n');
// Create a blob and initiate download
const blob = new Blob([uvContent], { type: 'text/plain;charset=utf-8' });
const filename = 'exported.uv1';
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
});
// Event listener for Load button
loadUVButton.addEventListener('click', () => {
uvLoader.click();
});
// Handle UV file loading
uvLoader.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
// Read the file content
const reader = new FileReader();
reader.onload = (event) => {
const content = event.target.result;
loadUVData(content);
};
reader.readAsText(file);
});
// Function to load UV data from content
function loadUVData(uvContent) {
const lines = uvContent.split('\n').map(line => line.trim()).filter(line => line.length > 0);
if (lines.length < 1) {
alert('Invalid .uv1 file format.');
return;
}
// Parse image size
const sizeParts = lines[0].split(',');
if (sizeParts.length !== 3 || sizeParts[0] !== 'size') {
alert('Invalid image size in .uv1 file.');
return;
}
const imgWidth = parseFloat(sizeParts[1]);
const imgHeight = parseFloat(sizeParts[2]);
if (!image.src) {
alert('Please import an image first.');
return;
}
// Check if image dimensions match
if (image.width !== imgWidth || image.height !== imgHeight) {
alert('The image size does not match the selections in the .uv1 file.');
return;
}
// Clear existing selections
selections = {};
// Parse face data
for (let i = 1; i < lines.length; i++) {
const parts = lines[i].split(',');
if (parts.length !== 5) {
alert(`Invalid data on line ${i + 1} in .uv1 file.`);
return;
}
const faceName = parts[0];
if (!faces.includes(faceName)) {
alert(`Unknown face name "${faceName}" on line ${i + 1}.`);
return;
}
const x = parseFloat(parts[1]);
const y = parseFloat(parts[2]);
const width = parseFloat(parts[3]);
const height = parseFloat(parts[4]);
if (width > 0 && height > 0) {
selections[faceName] = { x, y, width, height };
}
}
// Update face list buttons
const faceItems = faceList.getElementsByClassName('face-item');
Array.from(faceItems).forEach(item => {
const faceNameLabel = item.querySelector('.face-label').textContent;
const addButton = item.querySelector('button:nth-child(2)');
const deleteButton = item.querySelector('button:nth-child(3)');
const editButton = item.querySelector('button:nth-child(4)');
if (selections[faceNameLabel]) {
addButton.disabled = true;
deleteButton.disabled = false;
editButton.disabled = false;
} else {
addButton.disabled = false;
deleteButton.disabled = true;
editButton.disabled = true;
}
});
// Redraw canvas
draw();
}
</script>
</body>
</html>
Explanation of Changes:
-
Added Two New Buttons:
<!-- Add Load and Export buttons -->
<button id="loadUVButton">Load .uv1 File</button>
<input type="file" id="uvLoader" accept=".uv1" style="display:none"/>
<button id="exportUVButton">Export .uv1 File</button>
Load .uv1 File button allows the user to select a .uv1 file to load.
Export .uv1 File button triggers the export of the current selections to a .uv1 file.
- A hidden file input
uvLoader is used to handle file selection for loading.
-
Implemented Export Functionality:
// Event listener for Export button
exportUVButton.addEventListener('click', () => {
// ... (code to generate and download .uv1 file)
});
- Checks if an image is loaded.
- Generates the .uv1 file content based on the current selections.
- The first line contains the image size.
- The subsequent lines contain the face data in the specified format.
- Initiates a download of the generated .uv1 file.
-
Implemented Load Functionality:
loadUVButton.addEventListener('click', () => {
uvLoader.click();
});
uvLoader.addEventListener('change', (e) => {
// ... (code to read and parse the .uv1 file content)
});
function loadUVData(uvContent) {
// ... (code to parse the .uv1 file and update selections)
}
- Opens a file dialog to select a .uv1 file.
- Reads the content of the selected file.
- Parses the .uv1 file to extract the image size and face selections.
- Validates the image size to ensure it matches the loaded image.
- Updates the
selections object with the data from the .uv1 file.
- Updates the state of the face list buttons.
- Redraws the canvas to reflect the loaded selections.
-
Adjusted Event Handling and Drawing Functions:
- Modified the event handlers to ensure proper editing behavior, such as disabling the edit button during drawing.
- Added helper functions like
isInsideSelection to check if the mouse click is inside a selection.
- Ensured that when a selection is deleted or loaded, the face list buttons are updated accordingly.
-
Ensured Coordinate Consistency:
- When exporting and importing, the coordinates are based on the original image size, not the scaled or transformed positions.
Notes:
- The export functionality does not enforce that all faces are selected before exporting. If a face is not selected, its line in the .uv1 file will contain zeros for the rectangle coordinates and sizes.
- When loading a .uv1 file, if any face has zero width or height, it will not be added to the selections.
- The face list buttons are updated to reflect the current state of each face (whether it has a selection or not).
Usage:
-
To Export a .uv1 File:
- Ensure you have an image loaded and have made selections for the faces you want to export.
- Click the
Export .uv1 File button.
- The file
exported.uv1 will be downloaded to your computer.
-
To Load a .uv1 File:
- Ensure you have the same image loaded that was used when the .uv1 file was created.
- Click the
Load .uv1 File button.
- Select the .uv1 file from your computer.
- The selections will be loaded, and the canvas will update to show them.