I want to show preview image inside canvas-section. Give a button in the top left side of canvas-section container when it clicked the placement area will be hidden and mockup preview will be showen. By default placement area should be visible. The button should be wit icon. And it should be blend with the UI. Remove current preview button and preview section from code. Don't change any other code.
<!-- Rest of your existing HTML... -->
<div class="container">
<div class="canvas-section">
<div class="canvas-container">
<div class="canvas-wrapper">
<canvas id="mockupCanvas"></canvas>
<div id="placementArea" class="placement-area">
<div class="resize-handle top-left"></div>
<div class="resize-handle top-right"></div>
<div class="resize-handle bottom-left"></div>
<div class="resize-handle bottom-right"></div>
</div>
</div>
</div>
</div>
<div class="controls-section">
<div class="upload-section">
<h3>Upload Mockup Template</h3>
<div class="file-input-wrapper">
<input type="file" id="mockupInput" accept="image/*">
<div class="file-input-button">
<i class="fas fa-upload"></i>
Choose Mockup Template
</div>
</div>
<!-- <div class="dimensions-info" id="mockupDimensions">
No mockup template uploaded
</div> -->
</div>
<div class="upload-section">
<h3>Upload Design Folder</h3>
<div class="file-input-wrapper">
<input type="file" id="designInput" webkitdirectory directory multiple>
<div class="file-input-button">
<i class="fas fa-folder-open"></i>
Choose Design Folder
</div>
</div>
</div>
<button onclick="processAllDesigns()">
<i class="fas fa-magic"></i>
Generate All Mockups
</button>
<button onclick="previewDesign()">
<i class="fas fa-eye"></i>
Preview First Design
</button>
<div id="progress">
<div class="progress-bar">
<div class="progress-fill" id="progressFill"></div>
</div>
<div id="status">Ready to process</div>
</div>
<div class="preview">
<h3>Preview:</h3>
<canvas id="previewCanvas"></canvas>
</div>
</div>
</div>
<!-- Include JSZip Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script>
// Add theme toggle functionality
function toggleTheme() {
const html = document.documentElement;
const themeToggle = document.querySelector('.theme-toggle i');
if (html.getAttribute('data-theme') === 'dark') {
html.removeAttribute('data-theme');
themeToggle.className = 'fas fa-sun';
} else {
html.setAttribute('data-theme', 'dark');
themeToggle.className = 'fas fa-moon';
}
}
// Your existing MockupGenerator class and initialization...
class MockupGenerator {
constructor() {
this.initializeElements();
this.initializeState();
this.addEventListeners();
}
// Initialize DOM elements
initializeElements() {
this.canvas = document.getElementById('mockupCanvas');
this.ctx = this.canvas.getContext('2d');
this.previewCanvas = document.getElementById('previewCanvas');
this.previewCtx = this.previewCanvas.getContext('2d');
this.progressFill = document.getElementById('progressFill');
this.statusText = document.getElementById('status');
this.placementArea = document.getElementById('placementArea');
this.mockupDimensions = document.getElementById('mockupDimensions');
}
// Initialize application state
initializeState() {
this.mockupImage = null;
this.designs = [];
this.isDragging = false;
this.isResizing = false;
this.currentHandle = null;
this.startX = 0;
this.startY = 0;
this.startAreaX = 0;
this.startAreaY = 0;
this.startAreaWidth = 0;
this.startAreaHeight = 0;
this.scaleFactor = 1;
// Initial placement area dimensions (can be adjusted or set dynamically)
this.areaX = 186; // Canvas coordinate
this.areaY = 189; // Canvas coordinate
this.areaWidth = 707; // Canvas coordinate
this.areaHeight = 588; // Canvas coordinate
}
// Add necessary event listeners
addEventListeners() {
window.addEventListener('resize', () => this.handleWindowResize());
// File inputs
document.getElementById('mockupInput').addEventListener('change', (e) => this.handleMockupUpload(e));
document.getElementById('designInput').addEventListener('change', (e) => this.handleDesignUpload(e));
// Drag and Resize
this.placementArea.addEventListener('mousedown', (e) => this.handlePlacementAreaMouseDown(e));
// Resize handles
const resizeHandles = this.placementArea.querySelectorAll('.resize-handle');
resizeHandles.forEach(handle => {
handle.addEventListener('mousedown', (e) => this.handleResizeHandleMouseDown(e, handle));
});
// Mouse move and up on the document
document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
document.addEventListener('mouseup', () => this.handleMouseUp());
}
// Handle window resize to adjust canvas and placement area
handleWindowResize() {
if (this.mockupImage) {
this.updateCanvasDisplaySize();
}
}
// Handle mockup image upload
async handleMockupUpload(event) {
const file = event.target.files[0];
if (!file) return;
try {
this.mockupImage = await this.loadImage(file);
this.canvas.width = this.mockupImage.width;
this.canvas.height = this.mockupImage.height;
this.updateCanvasDisplaySize();
this.drawMockup();
// this.mockupDimensions.textContent = `Mockup dimensions: ${this.mockupImage.width}px × ${this.mockupImage.height}px`;
// Initialize preview canvas
this.previewCanvas.width = this.mockupImage.width;
this.previewCanvas.height = this.mockupImage.height;
this.previewCanvas.style.width = '100%';
this.previewCanvas.style.height = 'auto';
} catch (error) {
console.error('Error loading mockup image:', error);
alert('Failed to load mockup image. Please try a different file.');
}
}
// Handle design folder upload
handleDesignUpload(event) {
this.designs = Array.from(event.target.files).filter(file => file.type.startsWith('image/'));
this.statusText.textContent = `${this.designs.length} designs ready to process`;
}
// Load image from file
loadImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = e.target.result;
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
// Update the display size of the canvas based on container size
updateCanvasDisplaySize() {
const container = this.canvas.parentElement.parentElement;
const containerWidth = container.clientWidth - 40; // Account for padding
const containerHeight = container.clientHeight - 40; // Account for padding
// Calculate scale factor to fit mockup image within container
this.scaleFactor = Math.min(containerWidth / this.mockupImage.width, containerHeight / this.mockupImage.height);
// Apply scaling via CSS
this.canvas.style.width = `${this.mockupImage.width * this.scaleFactor}px`;
this.canvas.style.height = `${this.mockupImage.height * this.scaleFactor}px`;
// Update placement area position and size
this.updatePlacementArea();
}
// Draw the mockup image onto the canvas
drawMockup() {
if (!this.mockupImage) return;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.drawImage(this.mockupImage, 0, 0, this.canvas.width, this.canvas.height);
}
// Update the placement area's CSS based on current canvas and area coordinates
updatePlacementArea() {
const displayedWidth = this.canvas.width * this.scaleFactor;
const displayedHeight = this.canvas.height * this.scaleFactor;
// Convert canvas coordinates to CSS pixels
const left = this.areaX * this.scaleFactor;
const top = this.areaY * this.scaleFactor;
const width = this.areaWidth * this.scaleFactor;
const height = this.areaHeight * this.scaleFactor;
// Clamp position to stay within the canvas
const clampedLeft = Math.max(0, Math.min(left, displayedWidth - width));
const clampedTop = Math.max(0, Math.min(top, displayedHeight - height));
this.placementArea.style.left = `${clampedLeft}px`;
this.placementArea.style.top = `${clampedTop}px`;
this.placementArea.style.width = `${width}px`;
this.placementArea.style.height = `${height}px`;
}
// Event handler for mousedown on the placement area (for dragging)
handlePlacementAreaMouseDown(event) {
if (event.target.classList.contains('resize-handle')) {
// If the target is a resize handle, do not initiate drag
return;
}
this.isDragging = true;
const rect = this.placementArea.getBoundingClientRect();
this.startX = event.clientX - rect.left;
this.startY = event.clientY - rect.top;
event.preventDefault();
}
// Event handler for mousedown on a resize handle
handleResizeHandleMouseDown(event, handle) {
this.isResizing = true;
this.currentHandle = handle;
// Store initial mouse position and placement area dimensions
this.startX = event.clientX;
this.startY = event.clientY;
this.startAreaX = this.areaX;
this.startAreaY = this.areaY;
this.startAreaWidth = this.areaWidth;
this.startAreaHeight = this.areaHeight;
event.stopPropagation();
event.preventDefault();
}
// Event handler for mousemove (handles both dragging and resizing)
handleMouseMove(event) {
if (this.isDragging) {
this.handleDrag(event);
} else if (this.isResizing) {
this.handleResize(event);
}
}
// Handle dragging of the placement area
handleDrag(event) {
const canvasRect = this.canvas.getBoundingClientRect();
// Calculate new position in canvas coordinates
let newLeft = (event.clientX - canvasRect.left - this.startX) / this.scaleFactor;
let newTop = (event.clientY - canvasRect.top - this.startY) / this.scaleFactor;
// Clamp to canvas boundaries
newLeft = Math.max(0, Math.min(newLeft, this.canvas.width - this.areaWidth));
newTop = Math.max(0, Math.min(newTop, this.canvas.height - this.areaHeight));
// Update placement area coordinates
this.areaX = newLeft;
this.areaY = newTop;
this.updatePlacementArea();
}
// Handle resizing of the placement area
handleResize(event) {
const dx = (event.clientX - this.startX) / this.scaleFactor;
const dy = (event.clientY - this.startY) / this.scaleFactor;
let newAreaX = this.startAreaX;
let newAreaY = this.startAreaY;
let newAreaWidth = this.startAreaWidth;
let newAreaHeight = this.startAreaHeight;
const minSize = 50; // Minimum size in canvas pixels
if (this.currentHandle.classList.contains('top-left')) {
newAreaX = this.startAreaX + dx;
newAreaY = this.startAreaY + dy;
newAreaWidth = this.startAreaWidth - dx;
newAreaHeight = this.startAreaHeight - dy;
} else if (this.currentHandle.classList.contains('top-right')) {
newAreaY = this.startAreaY + dy;
newAreaWidth = this.startAreaWidth + dx;
newAreaHeight = this.startAreaHeight - dy;
} else if (this.currentHandle.classList.contains('bottom-left')) {
newAreaX = this.startAreaX + dx;
newAreaWidth = this.startAreaWidth - dx;
newAreaHeight = this.startAreaHeight + dy;
} else if (this.currentHandle.classList.contains('bottom-right')) {
newAreaWidth = this.startAreaWidth + dx;
newAreaHeight = this.startAreaHeight + dy;
}
// Enforce minimum size
if (newAreaWidth < minSize) {
newAreaWidth = minSize;
if (this.currentHandle.classList.contains('top-left') || this.currentHandle.classList.contains('bottom-left')) {
newAreaX = this.startAreaX + (this.startAreaWidth - minSize);
}
}
if (newAreaHeight < minSize) {
newAreaHeight = minSize;
if (this.currentHandle.classList.contains('top-left') || this.currentHandle.classList.contains('top-right')) {
newAreaY = this.startAreaY + (this.startAreaHeight - minSize);
}
}
// Clamp to canvas boundaries
if (newAreaX < 0) {
newAreaWidth += newAreaX;
newAreaX = 0;
}
if (newAreaY < 0) {
newAreaHeight += newAreaY;
newAreaY = 0;
}
if (newAreaX + newAreaWidth > this.canvas.width) {
newAreaWidth = this.canvas.width - newAreaX;
}
if (newAreaY + newAreaHeight > this.canvas.height) {
newAreaHeight = this.canvas.height - newAreaY;
}
// Update placement area coordinates
this.areaX = newAreaX;
this.areaY = newAreaY;
this.areaWidth = newAreaWidth;
this.areaHeight = newAreaHeight;
this.updatePlacementArea();
}
// Event handler for mouseup to stop dragging/resizing
handleMouseUp() {
this.isDragging = false;
this.isResizing = false;
this.currentHandle = null;
}
// Draw mockup and designs on the main canvas
async drawMockupWithDesign(context, designImage) {
context.clearRect(0, 0, this.canvas.width, this.canvas.height);
context.drawImage(this.mockupImage, 0, 0, this.canvas.width, this.canvas.height);
// Calculate aspect ratio fit for the design image within the placement area
const [designWidth, designHeight] = this.calculateAspectRatioFit(
designImage.width,
designImage.height,
this.areaWidth,
this.areaHeight
);
// Center the design horizontally within the placement area
const x = this.areaX + (this.areaWidth - designWidth) / 2;
const y = this.areaY;
context.drawImage(designImage, x, y, designWidth, designHeight);
}
// Calculate aspect ratio fit
calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return [srcWidth * ratio, srcHeight * ratio];
}
// Preview the first design
async previewDesign() {
if (!this.mockupImage || this.designs.length === 0) {
alert('Please upload both mockup template and design files.');
return;
}
try {
const designImage = await this.loadImage(this.designs[0]);
await this.drawMockupWithDesign(this.previewCtx, designImage);
} catch (error) {
console.error('Error previewing design:', error);
alert('Failed to preview design. Please try a different file.');
}
}
// Process all designs and generate mockups
async processAllDesigns() {
if (!this.mockupImage || this.designs.length === 0) {
alert('Please upload both mockup template and design files.');
return;
}
const zip = new JSZip();
try {
for (let i = 0; i < this.designs.length; i++) {
this.updateProgress(i + 1, this.designs.length);
const designImage = await this.loadImage(this.designs[i]);
await this.drawMockupWithDesign(this.ctx, designImage);
const mockupBlob = await new Promise(resolve => {
this.canvas.toBlob(resolve, 'image/png', 1.0);
});
zip.file(`mockup_${this.designs[i].name}`, mockupBlob);
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = 'mockups.zip';
link.click();
this.statusText.textContent = 'All mockups generated and downloaded!';
} catch (error) {
console.error('Error processing designs:', error);
alert('Failed to process all designs. Please try again.');
}
}
// Update progress bar and status text
updateProgress(current, total) {
const percentage = (current / total) * 100;
this.progressFill.style.width = `${percentage}%`;
this.statusText.textContent = `Processing: ${current} of ${total} designs`;
}
}
// Initialize the application
const mockupGenerator = new MockupGenerator();
// Expose global functions for button clicks
window.processAllDesigns = () => mockupGenerator.processAllDesigns();
window.previewDesign = () => mockupGenerator.previewDesign();
</script>
To meet your requirements, we will add a button in the top left corner of the .canvas-section to toggle the visibility of the placement area and show a mockup preview. Additionally, I'll remove the existing preview button and preview section from the controls section. Here's the updated HTML and script:
HTML Modifications
Add a toggle button with an icon to the top left of the .canvas-section.
Remove the current preview button and preview section from the controls.