<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 class="rotate-line"></div>
<div class="rotate-handle">
<i class="fas fa-sync-alt"></i>
</div>
</div>
</div>
</div>
</div>
<div class="controls-section">
<div class="upload-section">
<h3>Upload Mockup Folder</h3>
<div class="file-input-wrapper">
<input type="file" id="mockupInput" webkitdirectory directory multiple>
<div class="file-input-button">
<i class="fas fa-folder-open"></i>
Choose Mockup Folder
</div>
</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>
<div class="option-row">
<div class="checkbox-wrapper">
<input type="checkbox" id="boundingBoxFit" class="custom-checkbox">
<label for="boundingBoxFit">Smart Fit</label>
</div>
<div class="tooltip-trigger">
<i class="fas fa-info-circle"></i>
<div class="tooltip-content">
Automatically fits the placement area to the visible content of your design, ignoring transparent spaces
</div>
</div>
</div>
<div class="mockup-selector">
<select id="mockupSelect" class="mockup-select">
<option value="">Select a mockup</option>
</select>
</div>
<button id="previewButton" onclick="togglePreview()">
<i class="fas fa-eye"></i>
Preview First Design
</button>
<button onclick="processAllDesigns()">
<i class="fas fa-magic"></i>
Generate All Mockups
</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>
</div>
<!-- Include JSZip Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script>
function toggleTheme() {
const html = document.documentElement;
const themeToggle = document.querySelector('.theme-toggle i');
if (html.getAttribute('data-theme') === 'light') {
html.removeAttribute('data-theme');
themeToggle.className = 'fas fa-moon';
} else {
html.setAttribute('data-theme', 'light');
themeToggle.className = 'fas fa-sun';
}
}
class MockupGenerator {
constructor() {
this.initializeElements();
this.initializeState();
this.addEventListeners();
this.isPreviewMode = false;
}
// Method remains the same as in the original code
initializeElements() {
this.canvas = document.getElementById('mockupCanvas');
this.ctx = this.canvas.getContext('2d');
this.progressFill = document.getElementById('progressFill');
this.statusText = document.getElementById('status');
this.placementArea = document.getElementById('placementArea');
this.previewButton = document.getElementById('previewButton');
this.mockupSelect = document.getElementById('mockupSelect');
}
initializeState() {
this.mockups = []; // Array to store multiple mockup images
this.mockupData = new Map(); // Map to store placement data for each mockup
this.currentMockupIndex = 0;
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;
this.isRotating = false;
this.rotation = 0;
this.rotateStartAngle = 0;
}
// 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());
const rotateHandle = this.placementArea.querySelector('.rotate-handle');
rotateHandle.addEventListener('mousedown', (e) => this.handleRotateHandleMouseDown(e));
document.getElementById('mockupInput').addEventListener('change', (e) => this.handleMockupFolderUpload(e));
this.mockupSelect.addEventListener('change', (e) => {
const index = parseInt(e.target.value);
if (!isNaN(index)) {
this.switchMockup(index);
}
});
document.addEventListener('mouseup', () => {
if (this.isDragging || this.isResizing || this.isRotating) {
this.savePlacementData();
}
this.isDragging = false;
this.isResizing = false;
this.isRotating = false;
this.currentHandle = null;
});
}
// Handle window resize to adjust canvas and placement area
handleWindowResize() {
if (this.mockupImage) {
this.updateCanvasDisplaySize();
}
}
getBoundingBox(context, width, height) {
const imageData = context.getImageData(0, 0, width, height);
const data = imageData.data;
let minX = width;
let minY = height;
let maxX = 0;
let maxY = 0;
// Scan through each pixel
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const alpha = data[((y * width + x) * 4) + 3];
if (alpha > 0) { // If pixel is not completely transparent
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
}
// Return null if no visible pixels were found
if (minX > maxX || minY > maxY) {
return null;
}
return {
x: minX,
y: minY,
width: maxX - minX + 1,
height: maxY - minY + 1
};
}
// Handle mockup folder upload
async handleMockupFolderUpload(event) {
const files = Array.from(event.target.files).filter(file => file.type.startsWith('image/'));
this.mockups = [];
this.mockupData.clear();
this.mockupSelect.innerHTML = '<option value="">Select a mockup</option>';
try {
for (let i = 0; i < files.length; i++) {
const mockupImage = await this.loadImage(files[i]);
this.mockups.push({
image: mockupImage,
name: files[i].name
});
// Initialize placement data for each mockup
this.mockupData.set(i, {
areaX: 186,
areaY: 189,
areaWidth: 707,
areaHeight: 588,
rotation: 0
});
// Add to dropdown
const option = document.createElement('option');
option.value = i;
option.textContent = files[i].name;
this.mockupSelect.appendChild(option);
}
if (this.mockups.length > 0) {
this.currentMockupIndex = 0;
this.mockupSelect.value = "0";
await this.switchMockup(0);
}
this.statusText.textContent = `${this.mockups.length} mockups loaded`;
} catch (error) {
console.error('Error loading mockups:', error);
alert('Failed to load some mockup images. Please try again.');
}
}
// Handle mockup image upload
async handleMockupUpload(event) {
const file = event.target.files[0];
if (!file) return;
try {
this.mockupImage = await this.loadImage(file);
// Additional error checks
if (!this.mockupImage.width || !this.mockupImage.height) {
throw new Error('Invalid image dimensions');
}
this.canvas.width = this.mockupImage.width;
this.canvas.height = this.mockupImage.height;
this.updateCanvasDisplaySize();
this.drawMockup();
} catch (error) {
console.error('Error loading mockup image:', error);
alert('Failed to load mockup image. Please try a different file.');
}
}
// Switch between mockups
async switchMockup(index) {
if (index < 0 || index >= this.mockups.length) return;
// Save current placement data before switching
if (this.currentMockupIndex !== index) {
this.savePlacementData();
}
this.currentMockupIndex = index;
const mockup = this.mockups[index];
let placementData = this.mockupData.get(index);
// If no placement data exists for this mockup, initialize with default values
if (!placementData) {
placementData = {
areaX: 186,
areaY: 189,
areaWidth: 707,
areaHeight: 588,
rotation: 0
};
this.mockupData.set(index, placementData);
}
// Update canvas dimensions
this.canvas.width = mockup.image.width;
this.canvas.height = mockup.image.height;
// Restore placement data for this mockup
this.areaX = placementData.areaX;
this.areaY = placementData.areaY;
this.areaWidth = placementData.areaWidth;
this.areaHeight = placementData.areaHeight;
this.rotation = placementData.rotation;
// Exit preview mode if active
if (this.isPreviewMode) {
this.exitPreview();
}
this.updateCanvasDisplaySize();
this.drawMockup();
this.updatePlacementArea();
this.placementArea.style.transform = `rotate(${this.rotation}deg)`;
}
// Save current placement data
savePlacementData() {
this.mockupData.set(this.currentMockupIndex, {
areaX: this.areaX,
areaY: this.areaY,
areaWidth: this.areaWidth,
areaHeight: this.areaHeight,
rotation: this.rotation
});
}
// 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.mockups.length) return;
const currentMockup = this.mockups[this.currentMockupIndex];
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.drawImage(currentMockup.image, 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`;
}
handleRotateHandleMouseDown(event) {
this.isRotating = true;
const rect = this.placementArea.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
// Store the initial angle and current rotation
this.rotateStartAngle = Math.atan2(event.clientY - centerY, event.clientX - centerX);
this.initialRotation = this.rotation || 0;
event.stopPropagation();
event.preventDefault();
}
handleRotate(event) {
const rect = this.placementArea.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const currentAngle = Math.atan2(event.clientY - centerY, event.clientX - centerX);
let angleDiff = (currentAngle - this.rotateStartAngle) * (180 / Math.PI);
// Calculate new rotation based on initial rotation plus the change
let newRotation = this.initialRotation + angleDiff;
// Add damping factor to make rotation smoother
const dampingFactor = 0.5; // Adjust this value between 0 and 1 for different sensitivity
newRotation = this.initialRotation + (angleDiff * dampingFactor);
// Snap to 15-degree intervals when holding Shift
if (event.shiftKey) {
newRotation = Math.round(newRotation / 15) * 15;
}
this.rotation = newRotation;
this.placementArea.style.transform = `rotate(${this.rotation}deg)`;
}
// 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);
} else if (this.isRotating) {
this.handleRotate(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.isRotating = 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);
// Create a temporary canvas to analyze the design image
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = designImage.width;
tempCanvas.height = designImage.height;
tempCtx.drawImage(designImage, 0, 0);
let designWidth = designImage.width;
let designHeight = designImage.height;
// If bounding box fit is enabled, get the actual content dimensions
if (document.getElementById('boundingBoxFit').checked) {
const boundingBox = this.getBoundingBox(tempCtx, designWidth, designHeight);
if (boundingBox) {
designWidth = boundingBox.width;
designHeight = boundingBox.height;
// Create another temp canvas for the cropped image
const croppedCanvas = document.createElement('canvas');
croppedCanvas.width = boundingBox.width;
croppedCanvas.height = boundingBox.height;
const croppedCtx = croppedCanvas.getContext('2d');
croppedCtx.drawImage(designImage,
boundingBox.x, boundingBox.y, boundingBox.width, boundingBox.height,
0, 0, boundingBox.width, boundingBox.height
);
// Create a new image from the cropped canvas
const croppedImage = new Image();
await new Promise(resolve => {
croppedImage.onload = resolve;
croppedImage.src = croppedCanvas.toDataURL();
});
designImage = croppedImage;
}
}
const [finalWidth, finalHeight] = this.calculateAspectRatioFit(
designWidth,
designHeight,
this.areaWidth,
this.areaHeight
);
const x = this.areaX + (this.areaWidth - finalWidth) / 2;
const y = this.areaY;
// Save the current context state
context.save();
// Translate to the center of the placement area
const centerX = x + finalWidth / 2;
const centerY = y + finalHeight / 2;
context.translate(centerX, centerY);
// Rotate
context.rotate(this.rotation * Math.PI / 180);
// Draw the image centered
context.drawImage(designImage, -finalWidth / 2, -finalHeight / 2, finalWidth, finalHeight);
// Restore the context state
context.restore();
}
// Calculate aspect ratio fit
calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return [srcWidth * ratio, srcHeight * ratio];
}
// Modify preview design method
async previewDesign() {
if (!this.mockups[this.currentMockupIndex] || this.designs.length === 0) {
alert('Please upload both mockup template and design files.');
return;
}
try {
const currentMockup = this.mockups[this.currentMockupIndex];
const designImage = await this.loadImage(this.designs[0]);
// Set canvas dimensions for current mockup
this.canvas.width = currentMockup.image.width;
this.canvas.height = currentMockup.image.height;
// Get placement data for current mockup
const placementData = this.mockupData.get(this.currentMockupIndex);
// Set the current mockup image
this.mockupImage = currentMockup.image;
// Apply placement data
this.areaX = placementData.areaX;
this.areaY = placementData.areaY;
this.areaWidth = placementData.areaWidth;
this.areaHeight = placementData.areaHeight;
this.rotation = placementData.rotation;
await this.drawMockupWithDesign(this.ctx, designImage);
// Toggle preview mode
this.placementArea.classList.add('hidden');
this.isPreviewMode = true;
this.previewButton.innerHTML = `<i class="fas fa-eye-slash"></i> Hide Preview`;
} catch (error) {
console.error('Error previewing design:', error);
alert('Failed to preview design. Please try a different file.');
}
}
// Method to exit preview mode
exitPreview() {
if (!this.mockupImage) return;
const currentMockup = this.mockups[this.currentMockupIndex];
// Make sure we're using the current mockup image
this.mockupImage = currentMockup.image;
this.drawMockup();
this.placementArea.classList.remove('hidden');
this.isPreviewMode = false;
this.previewButton.innerHTML = `<i class="fas fa-eye"></i> Preview First Design`;
}
// Process all designs and generate mockups
async processAllDesigns() {
if (this.mockups.length === 0 || this.designs.length === 0) {
alert('Please upload both mockup templates and design files.');
return;
}
const zip = new JSZip();
const total = this.mockups.length * this.designs.length;
let current = 0;
// Save current mockup index to restore later
const originalMockupIndex = this.currentMockupIndex;
try {
// First loop through mockups, then designs
for (let mockupIndex = 0; mockupIndex < this.mockups.length; mockupIndex++) {
const mockup = this.mockups[mockupIndex];
const placementData = this.mockupData.get(mockupIndex);
// Set up canvas and placement data for this mockup
this.canvas.width = mockup.image.width;
this.canvas.height = mockup.image.height;
this.mockupImage = mockup.image;
// Apply placement data
this.areaX = placementData.areaX;
this.areaY = placementData.areaY;
this.areaWidth = placementData.areaWidth;
this.areaHeight = placementData.areaHeight;
this.rotation = placementData.rotation;
// Process each design for this mockup
for (let designIndex = 0; designIndex < this.designs.length; designIndex++) {
const design = this.designs[designIndex];
const designImage = await this.loadImage(design);
// Draw mockup with design
await this.drawMockupWithDesign(this.ctx, designImage);
// Save to zip
const mockupBlob = await new Promise(resolve => {
this.canvas.toBlob(resolve, 'image/png', 1.0);
});
// Create a descriptive filename
const fileName = `mockup${mockupIndex + 1}_${mockup.name}_design${designIndex + 1}_${design.name}.png`;
zip.file(fileName, mockupBlob);
current++;
this.updateProgress(current, total);
}
}
// Generate and download zip
const zipBlob = await zip.generateAsync({ type: 'blob' });
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = 'mockups.zip';
link.click();
// Clean up
URL.revokeObjectURL(link.href);
// Restore original mockup state
await this.switchMockup(originalMockupIndex);
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.');
// Restore original mockup state even if there's an error
await this.switchMockup(originalMockupIndex);
}
}
// 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();
// Global function to toggle preview
function togglePreview() {
if (mockupGenerator.isPreviewMode) {
mockupGenerator.exitPreview();
} else {
mockupGenerator.previewDesign();
}
}
// Expose global functions for button clicks
window.processAllDesigns = () => mockupGenerator.processAllDesigns();
window.previewDesign = () => mockupGenerator.previewDesign();
window.togglePreview = togglePreview;
</script>
Hello,
I understand that you're experiencing an issue where, after pressing Preview, you're unable to change the placement area—the placement stays where it was initially, and you can't edit it further.
The root cause of this issue lies in the canvas scaling and placement area updates when exiting the preview mode. When you enter preview mode, certain adjustments are made to the canvas and placement area to display the design on the mockup. However, upon exiting the preview, these adjustments aren't fully reverted, leading to the placement area becoming unresponsive.
Solution
To fix this issue, you need to update the canvas display size and placement area after exiting the preview mode. This ensures that the placement area is correctly positioned and can be interacted with again.
Here's how you can modify your exitPreview method:
- Call
updateCanvasDisplaySize() to recalculate the canvas display size and scaling factor.
- Call
updatePlacementArea() to reposition and resize the placement area based on the new canvas size.
- Reset the placement area's rotation to ensure it's correctly oriented.
Updated exitPreview Method
Replace your existing exitPreview method with the following code:
exitPreview() {
if (!this.mockupImage) return;
const currentMockup = this.mockups[this.currentMockupIndex];
// Use the current mockup image
this.mockupImage = currentMockup.image;
// Redraw the mockup
this.drawMockup();
// Update the canvas display size and placement area
this.updateCanvasDisplaySize();
this.updatePlacementArea();
// Reset the placement area's rotation
this.placementArea.style.transform = `rotate(${this.rotation}deg)`;
// Show the placement area
this.placementArea.classList.remove('hidden');
this.isPreviewMode = false;
this.previewButton.innerHTML = `<i class="fas fa-eye"></i> Preview First Design`;
}
Explanation
-
this.updateCanvasDisplaySize();
- This recalculates the canvas scaling factor and adjusts the canvas's display size to match the container. It's essential because, during preview mode, the canvas may have been resized, and we need to reset it to the correct size after exiting preview.
-
this.updatePlacementArea();
- This updates the placement area's CSS properties (
top, left, width, height) based on the new canvas size and scaling factor. It ensures that the placement area aligns correctly on the canvas and becomes interactive again.
-
this.placementArea.style.transform = \rotate(${this.rotation}deg)`;`
- This resets the rotation of the placement area to the previously stored rotation value.
By adding these lines, you ensure that the placement area is properly re-initialized after exiting the preview mode, allowing you to edit it again.
Additional Considerations
Testing the Solution
-
Implement the Updated exitPreview Method
- Replace the existing method in your JavaScript code with the updated version provided above.
-
Test the Workflow
- Upload a mockup image or folder.
- Upload design files.
- Adjust the placement area to a desired position and size.
- Click on Preview to see the design applied to the mockup.
- Exit Preview mode by clicking the preview button again.
- Attempt to adjust the placement area once more.
-
Verify Functionality
- Ensure that after exiting the preview mode, the placement area is responsive.
- Confirm that you can drag, resize, and rotate the placement area as before.
Why This Fix Works
When you enter preview mode, the canvas and placement area are modified to display the design superimposed on the mockup. However, without updating the canvas display size and placement area upon exiting preview, there remains a mismatch between the actual canvas size and its displayed size. This leads to incorrect calculations for interactions like dragging and resizing.
By updating the canvas display size and placement area, you realign the visual elements with their actual dimensions, ensuring that user interactions are accurately mapped.
Conclusion
Applying these changes should resolve the issue you're experiencing, allowing you to edit the placement area after previewing. If you have any further questions or run into any other issues, feel free to ask!
Happy Coding! 🚀