Certainly! Below is an HTML code that implements the functionality you've described. This code uses pure HTML, CSS, and JavaScript to create an interactive interface where users can import an image, select rectangles representing the faces of a box, and manage these selections through a list of controls.
For better performance and functionality, we're using the HTML5 Canvas element for rendering the image and the selections. We handle zooming, panning, and selection logic with JavaScript.
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Box Packaging Design Selector</title>
<style>
body, html {
margin: 0;
overflow: hidden;
height: 100%;
}
#canvas-container {
position: relative;
width: 100%;
height: 100%;
background-color: #f0f0f0;
cursor: crosshair;
}
#myCanvas {
position: absolute;
left: 0;
top: 0;
}
#controls {
position: absolute;
top: 10px;
left: 10px;
background: rgba(255,255,255,0.9);
padding: 10px;
border-radius: 5px;
}
#face-list {
margin-top: 10px;
}
.face-item {
display: flex;
align-items: center;
margin-bottom: 5px;
}
.face-item label {
margin-right: 10px;
}
.face-item button {
margin-left: 5px;
}
</style>
</head>
<body>
<div id="canvas-container">
<canvas id="myCanvas"></canvas>
<div id="controls">
<input type="file" id="imageLoader" accept="image/*"/>
<div id="face-list">
<!-- Face controls will be dynamically added here -->
</div>
</div>
</div>
<script>
// JavaScript code will go here
</script>
</body>
</html>
JavaScript Code:
Place the following JavaScript code inside the <script> tag at the bottom of your HTML file.
// Get references to HTML elements
const canvasContainer = document.getElementById('canvas-container');
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const imageLoader = document.getElementById('imageLoader');
const faceList = document.getElementById('face-list');
let image = new Image();
let imageScale = 1;
let offsetX, offsetY;
let isDragging = false;
let dragStart = { x: 0, y: 0 };
let translatePos = { x: 0, y: 0 };
let faces = {}; // Store face selections
let currentFace = null;
let isEditing = false;
// List of face names
const faceNames = ['Front', 'Back', 'Right', 'Left', 'Top', 'Bottom'];
// Set canvas size to fill the container
function resizeCanvas() {
canvas.width = canvasContainer.clientWidth;
canvas.height = canvasContainer.clientHeight;
draw();
}
// Load image when a file is selected
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e){
const reader = new FileReader();
reader.onload = function(event){
image.onload = function(){
resetTransformations();
addFaceControls();
draw();
}
image.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
// Reset transformations
function resetTransformations() {
imageScale = 1;
translatePos = { x: 0, y: 0 };
faces = {};
currentFace = null;
isEditing = false;
}
// Add face controls to the list
function addFaceControls() {
faceList.innerHTML = '';
faceNames.forEach(faceName => {
const faceItem = document.createElement('div');
faceItem.className = 'face-item';
const label = document.createElement('label');
label.textContent = faceName;
const addBtn = document.createElement('button');
addBtn.textContent = 'Add Face';
addBtn.addEventListener('click', () => addFace(faceName));
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete Face';
deleteBtn.disabled = true;
deleteBtn.addEventListener('click', () => deleteFace(faceName));
const editBtn = document.createElement('button');
editBtn.textContent = 'Edit Face';
editBtn.disabled = true;
editBtn.addEventListener('click', () => editFace(faceName));
faceItem.appendChild(label);
faceItem.appendChild(addBtn);
faceItem.appendChild(deleteBtn);
faceItem.appendChild(editBtn);
faceList.appendChild(faceItem);
faces[faceName] = null;
faceItem.dataset.faceName = faceName;
faceItem.dataset.addBtn = addBtn;
faceItem.dataset.deleteBtn = deleteBtn;
faceItem.dataset.editBtn = editBtn;
});
}
// Handle canvas interactions
canvas.addEventListener('mousedown', function(e) {
const mousePos = getMousePos(e);
if (e.button === 1) {
// Middle mouse button for dragging
isDragging = true;
dragStart.x = mousePos.x - translatePos.x;
dragStart.y = mousePos.y - translatePos.y;
} else if (e.button === 0 && currentFace && isEditing) {
// Left mouse button for selection
const face = faces[currentFace];
if (face) {
face.isResizing = true;
face.resizeStart = { x: mousePos.x, y: mousePos.y };
} else {
faces[currentFace] = {
x: (mousePos.x - translatePos.x) / imageScale,
y: (mousePos.y - translatePos.y) / imageScale,
width: 0,
height: 0,
isResizing: true,
resizeStart: { x: mousePos.x, y: mousePos.y },
};
}
}
});
canvas.addEventListener('mousemove', function(e) {
const mousePos = getMousePos(e);
if (isDragging) {
translatePos.x = mousePos.x - dragStart.x;
translatePos.y = mousePos.y - dragStart.y;
draw();
} else if (currentFace && isEditing) {
const face = faces[currentFace];
if (face && face.isResizing) {
const x = (mousePos.x - translatePos.x) / imageScale;
const y = (mousePos.y - translatePos.y) / imageScale;
face.width = x - face.x;
face.height = y - face.y;
draw();
}
}
});
canvas.addEventListener('mouseup', function(e) {
isDragging = false;
if (currentFace && isEditing) {
const face = faces[currentFace];
if (face) {
face.isResizing = false;
updateFaceButtons();
}
}
});
canvas.addEventListener('wheel', function(e) {
e.preventDefault();
const mousePos = getMousePos(e);
const zoom = e.deltaY < 0 ? 1.1 : 0.9;
const newScale = imageScale * zoom;
const mx = mousePos.x - translatePos.x;
const my = mousePos.y - translatePos.y;
translatePos.x -= mx * (zoom - 1);
translatePos.y -= my * (zoom - 1);
imageScale = newScale;
draw();
});
// Get mouse position relative to the canvas
function getMousePos(evt) {
const rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
// Draw the image and selections on the canvas
function draw() {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0); // Reset transform
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
ctx.restore();
ctx.save();
ctx.translate(translatePos.x, translatePos.y);
ctx.scale(imageScale, imageScale);
if (image) {
ctx.drawImage(image, 0, 0);
}
// Draw face selections
for (let faceName in faces) {
const face = faces[faceName];
if (face) {
ctx.strokeStyle = 'red';
ctx.lineWidth = 2 / imageScale;
ctx.strokeRect(face.x, face.y, face.width, face.height);
// Draw face name at the center
ctx.fillStyle = 'red';
ctx.font = `${20 / imageScale}px Arial`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(faceName, face.x + face.width / 2, face.y + face.height / 2);
}
}
ctx.restore();
}
// Add a face selection
function addFace(faceName) {
currentFace = faceName;
isEditing = true;
updateFaceButtons();
}
// Delete a face selection
function deleteFace(faceName) {
faces[faceName] = null;
if (currentFace === faceName) {
currentFace = null;
isEditing = false;
}
updateFaceButtons();
draw();
}
// Edit a face selection
function editFace(faceName) {
currentFace = faceName;
isEditing = true;
updateFaceButtons();
}
// Update the state of face buttons
function updateFaceButtons() {
const faceItems = faceList.getElementsByClassName('face-item');
for (let item of faceItems) {
const faceName = item.querySelector('label').textContent;
const addBtn = item.querySelector('button:nth-child(2)');
const deleteBtn = item.querySelector('button:nth-child(3)');
const editBtn = item.querySelector('button:nth-child(4)');
if (faces[faceName]) {
addBtn.disabled = true;
deleteBtn.disabled = false;
editBtn.disabled = false;
} else {
addBtn.disabled = false;
deleteBtn.disabled = true;
editBtn.disabled = true;
}
if (currentFace === faceName && isEditing) {
editBtn.textContent = 'Stop Editing';
} else {
editBtn.textContent = 'Edit Face';
}
}
}
// Initial setup
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
Explanation:
- Canvas and Context Initialization: We set up the canvas to fill the container and get its 2D drawing context.
- Image Loading: When the user selects an image, we load it and reset any transformations or previous selections.
- Panning and Zooming:
- Panning: We use the middle mouse button (button === 1) to allow the user to drag the image around. The
translatePos object keeps track of the translation offsets.
- Zooming: We listen for the
wheel event and adjust the imageScale variable accordingly. We also adjust the translation offsets so that zooming focuses on the cursor position.
- Selection of Faces:
- Adding a Face: When the user clicks "Add Face," they can draw a rectangle on the image to represent that face.
- Editing a Face: Clicking "Edit Face" allows the user to modify the dimensions of the existing selection.
- Deleting a Face: Removes the selection associated with that face.
- Selection Rectangle: As the user drags the mouse, we update the width and height of the rectangle representing the face.
- Drawing on Canvas:
- We scale and translate the context according to
imageScale and translatePos before drawing.
- We draw the image and then iterate over the
faces object to draw each face selection rectangle and label.
- User Interface Controls:
- The controls for adding, deleting, and editing faces are dynamically generated based on the
faceNames array.
- We update the state of the buttons based on whether a face has been added or is currently being edited.
Notes:
- Middle Mouse Button Dragging: Some browsers and systems may have default behaviors for the middle mouse button. Make sure to test this functionality, and consider using an alternative (e.g., holding a key while dragging) if needed.
- Edge Handles for Resizing: For simplicity, this implementation allows resizing from one corner. Implementing edge and corner handles would require more complex hit-testing and is beyond the scope of this example.
- Further Enhancements:
- Edge and Corner Handles: Implement interactive handles for more precise resizing.
- Persisting Selections: Allow exporting or saving the selection data.
- Validation: Ensure that selection rectangles don't overlap or exceed image boundaries.
- Improved User Experience: Provide visual feedback during interactions, such as cursor changes or highlighting selected faces.
This code provides a foundational implementation of the requested functionality. You can further enhance it by adding more sophisticated features as needed.