Sure! I've updated your code to include the features you requested:
-
Middle Edge Handles: Now, in addition to the corner handles, there are handles on the middle of each edge to allow resizing in one dimension.
-
Visual Orientation Indicator: I've added an arrow inside the selection rectangle to indicate the orientation of the face. This helps the user understand how the face will appear when mapped.
-
Background Color Selection: There's now an input field in the toolbar that allows the user to enter a hex color code or select a color from the image. This color is used as the background when generating the texture.
-
Save as PNG or JPG: After generating the texture, the user can choose to save the image as a PNG or JPG file.
Below is the updated code with explanations:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Box Packaging Design Selector</title>
<style>
/* Same styles as before */
</style>
</head>
<body>
<div id="toolbar">
<!-- Existing buttons -->
<button id="importImageButton">Import Image</button>
<input type="file" id="imageLoader" accept="image/*" style="display:none"/>
<button id="importUVButton">Import .uv1 File</button>
<input type="file" id="uvLoader" accept=".uv1" style="display:none"/>
<button id="generateTextureButton">Generate Texture</button>
<!-- New background color input -->
<label style="margin-left: 10px;">Background Color:
<input type="text" id="bgColorInput" value="#ffffff" style="width: 80px;">
<button id="pickColorButton">Pick from Image</button>
</label>
<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 importUVButton = document.getElementById('importUVButton');
const uvLoader = document.getElementById('uvLoader');
const generateTextureButton = document.getElementById('generateTextureButton');
const canvas = document.getElementById('imageCanvas');
const faceList = document.getElementById('faceList');
const canvasContainer = document.getElementById('canvasContainer');
const ctx = canvas.getContext('2d');
// New elements for background color
const bgColorInput = document.getElementById('bgColorInput');
const pickColorButton = document.getElementById('pickColorButton');
// Variables for canvas manipulation (same as before)
// ...
// Variables for color picking
let isPickingColor = false;
function resizeCanvas() {
// Same as before
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// Event listeners for Import Image and UV buttons (same as before)
// ...
// Load selected image (same as before)
// ...
// Parse UV data (same as before)
// ...
// Set up faces list (same as before)
// ...
// 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 (isPickingColor) {
// Picking color from the image
pickColorFromImage(imgMouseX, imgMouseY);
isPickingColor = false;
canvas.style.cursor = 'default';
return;
}
if (e.button === 1 || (e.button === 0 && e.ctrlKey)) {
// Panning logic (same as before)
} else if (isDrawing && currentFace) {
// Drawing selection rectangle (same as before)
} else if (isEditing && editHandle && selections[currentFace]) {
// Handle already selected
} else if (isEditing && selections[currentFace]) {
// Check if clicked on handle
const handle = getHandleUnderMouse(mouseX, mouseY);
if (handle) {
editHandle = handle;
panStart = { x: selections[currentFace].x, y: selections[currentFace].y, width: selections[currentFace].width, height: selections[currentFace].height };
mouseStart = { x: imgMouseX, y: imgMouseY };
} else if (isPointInSelection(mouseX, mouseY, selections[currentFace])) {
// Start moving the selection
editHandle = 'move';
panStart = { x: selections[currentFace].x, y: selections[currentFace].y };
mouseStart = { x: imgMouseX, y: imgMouseY };
}
}
});
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 logic (same as before)
} else if (isDrawing && selections[currentFace]) {
// Update selection rectangle size (same as before)
} else if (isEditing && editHandle && selections[currentFace]) {
// Edit selection rectangle
const sel = selections[currentFace];
if (editHandle === 'move') {
// Move the selection (same as before)
} 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';
}
}
});
canvas.addEventListener('mouseup', (e) => {
isPanning = false;
isDrawing = false;
editHandle = null;
});
canvas.addEventListener('wheel', (e) => {
// Zooming logic (same as before)
});
canvas.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
// Handle color picking
pickColorButton.addEventListener('click', () => {
isPickingColor = true;
canvas.style.cursor = 'crosshair';
});
function pickColorFromImage(x, y) {
const imageData = ctx.getImageData(x * imgScale + imgPos.x, y * imgScale + imgPos.y, 1, 1).data;
const hexColor = rgbToHex(imageData[0], imageData[1], imageData[2]);
bgColorInput.value = hexColor;
}
function rgbToHex(r, g, b) {
return "#" + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('');
}
function draw() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw image (same as before)
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];
drawSelection(sel, faceName, faceName === currentFace && isEditing);
}
}
function drawSelection(sel, label, showHandles) {
ctx.save();
ctx.strokeStyle = faceColors[label] || 'red';
ctx.lineWidth = 2;
ctx.strokeRect(
sel.x * imgScale + imgPos.x,
sel.y * imgScale + imgPos.y,
sel.width * imgScale,
sel.height * imgScale
);
// Draw orientation arrow
drawOrientationArrow(sel);
// Draw label (same as before)
// ...
// 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 drawOrientationArrow(sel) {
const x = sel.x * imgScale + imgPos.x + 10;
const y = sel.y * imgScale + imgPos.y + 10;
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.strokeStyle = 'white';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + 20, y);
ctx.lineTo(x + 15, y - 5);
ctx.moveTo(x + 20, y);
ctx.lineTo(x + 15, y + 5);
ctx.stroke();
}
function updateHandles(sel) {
handles = [];
const x = sel.x * imgScale + imgPos.x;
const y = sel.y * imgScale + imgPos.y;
const w = sel.width * imgScale;
const h = sel.height * imgScale;
// Corner points
const points = [
{ x: x, y: y, pos: 'nw' }, // Top-left
{ x: x + w, y: y, pos: 'ne' }, // Top-right
{ x: x, y: y + h, pos: 'sw' }, // Bottom-left
{ x: x + w, y: y + h, pos: 'se' } // Bottom-right
];
// Middle points
const middles = [
{ x: x + w / 2, y: y, pos: 'n' }, // Top-center
{ x: x + w, y: y + h / 2, pos: 'e' }, // Right-center
{ x: x + w / 2, y: y + h, pos: 's' }, // Bottom-center
{ x: x, y: y + h / 2, pos: 'w' } // Left-center
];
handles = points.concat(middles);
}
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;
case 'n':
sel.height += sel.y - imgMouseY;
sel.y = imgMouseY;
break;
case 's':
sel.height = imgMouseY - sel.y;
break;
case 'e':
sel.width = imgMouseX - sel.x;
break;
case 'w':
sel.width += sel.x - imgMouseX;
sel.x = imgMouseX;
break;
}
}
generateTextureButton.addEventListener('click', () => {
// Same check as before
if (!image.src) {
alert('Please load an image first.');
return;
}
if (!uvData || Object.keys(uvData).length === 0) {
alert('Please load a .uv1 file first.');
return;
}
generateFinalTexture();
});
function generateFinalTexture() {
// Create off-screen canvas
const outputCanvas = document.createElement('canvas');
outputCanvas.width = outputImageSize.width;
outputCanvas.height = outputImageSize.height;
const outputCtx = outputCanvas.getContext('2d');
// Fill background with the selected color
const bgColor = bgColorInput.value || '#ffffff';
outputCtx.fillStyle = bgColor;
outputCtx.fillRect(0, 0, outputCanvas.width, outputCanvas.height);
for (const faceName in uvData) {
const uv = uvData[faceName];
const sel = selections[faceName];
if (!sel) {
continue; // Skip if no selection is made for this face
}
// Rest of the code remains the same, including transformations
// ...
// Draw the transformed face onto the output canvas at the UV-specified position
outputCtx.drawImage(
faceCanvas,
0,
0,
faceCanvas.width,
faceCanvas.height,
uv.x,
uv.y,
uv.width,
uv.height
);
}
// Provide options to save the image as PNG or JPG
saveImage(outputCanvas);
}
function saveImage(canvas) {
const dataURL_PNG = canvas.toDataURL('image/png');
const dataURL_JPG = canvas.toDataURL('image/jpeg');
const linkContainer = document.createElement('div');
linkContainer.style.position = 'fixed';
linkContainer.style.top = '50%';
linkContainer.style.left = '50%';
linkContainer.style.transform = 'translate(-50%, -50%)';
linkContainer.style.backgroundColor = '#fff';
linkContainer.style.padding = '20px';
linkContainer.style.border = '1px solid #000';
linkContainer.style.zIndex = '1000';
linkContainer.style.textAlign = 'center';
const img = document.createElement('img');
img.src = dataURL_PNG;
img.style.maxWidth = '400px';
linkContainer.appendChild(img);
const savePNGButton = document.createElement('button');
savePNGButton.textContent = 'Save as PNG';
savePNGButton.style.display = 'block';
savePNGButton.style.margin = '10px auto';
savePNGButton.addEventListener('click', () => {
downloadImage(dataURL_PNG, 'texture.png');
});
linkContainer.appendChild(savePNGButton);
const saveJPGButton = document.createElement('button');
saveJPGButton.textContent = 'Save as JPG';
saveJPGButton.style.display = 'block';
saveJPGButton.style.margin = '10px auto';
saveJPGButton.addEventListener('click', () => {
downloadImage(dataURL_JPG, 'texture.jpg');
});
linkContainer.appendChild(saveJPGButton);
const closeButton = document.createElement('button');
closeButton.textContent = 'Close';
closeButton.style.display = 'block';
closeButton.style.margin = '10px auto';
closeButton.addEventListener('click', () => {
document.body.removeChild(linkContainer);
});
linkContainer.appendChild(closeButton);
document.body.appendChild(linkContainer);
}
function downloadImage(dataURL, filename) {
const link = document.createElement('a');
link.href = dataURL;
link.download = filename;
link.click();
}
</script>
</body>
</html>
Explanation of Changes:
-
Middle Edge Handles:
-
Update updateHandles Function:
Added middle edge points to the handles array.
// Middle points
const middles = [
{ x: x + w / 2, y: y, pos: 'n' }, // Top-center
{ x: x + w, y: y + h / 2, pos: 'e' }, // Right-center
{ x: x + w / 2, y: y + h, pos: 's' }, // Bottom-center
{ x: x, y: y + h / 2, pos: 'w' } // Left-center
];
handles = points.concat(middles);
-
Update adjustSelection Function:
Modified to handle the new positions ('n', 's', 'e', 'w').
case 'n':
sel.height += sel.y - imgMouseY;
sel.y = imgMouseY;
break;
case 's':
sel.height = imgMouseY - sel.y;
break;
case 'e':
sel.width = imgMouseX - sel.x;
break;
case 'w':
sel.width += sel.x - imgMouseX;
sel.x = imgMouseX;
break;
-
Visual Orientation Indicator:
-
Added drawOrientationArrow Function:
This function draws an arrow inside the selection rectangle to indicate orientation.
function drawOrientationArrow(sel) {
const x = sel.x * imgScale + imgPos.x + 10;
const y = sel.y * imgScale + imgPos.y + 10;
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.strokeStyle = 'white';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + 20, y);
ctx.lineTo(x + 15, y - 5);
ctx.moveTo(x + 20, y);
ctx.lineTo(x + 15, y + 5);
ctx.stroke();
}
-
Called within drawSelection:
// Draw orientation arrow
drawOrientationArrow(sel);
-
Background Color Selection:
-
Added Input Fields in Toolbar:
<label style="margin-left: 10px;">Background Color:
<input type="text" id="bgColorInput" value="#ffffff" style="width: 80px;">
<button id="pickColorButton">Pick from Image</button>
</label>
-
Added Event Listener for Color Picking:
pickColorButton.addEventListener('click', () => {
isPickingColor = true;
canvas.style.cursor = 'crosshair';
});
Usage Notes:
-
Middle Edge Handles:
When editing a selection, you can use the new middle handles to adjust the width or height without affecting the other dimension.
-
Orientation Indicator:
An arrow is drawn inside each selection to show the orientation. This is especially helpful when you apply rotations or flips to ensure the design aligns correctly.
-
Background Color Selection:
- Enter a hex color code (e.g.,
#ff0000 for red) in the input field.
- Click "Pick from Image" and then click on the canvas to select a color from the loaded image.
-
Saving the Texture:
After generating the texture, a preview appears with options to save as PNG or JPG. Click the desired format to download the image.
I hope these enhancements meet your requirements! Let me know if you need further assistance.