基于object-fit:cover的单图多比例裁剪展示界面实现问询
Hey there! Let's build your image preview tool step by step—since you're new to JavaScript and this stack, I'll make sure each part is clear and easy to follow. We'll cover the UI with object-fit: cover, local file handling via the File API, and deploying it with Google Apps Script so you can access it easily.
Step 1: Basic HTML Structure
First, let's set up the core HTML. We'll need a file input to select local images, and a container to hold our different aspect ratio previews:
<!DOCTYPE html> <html> <head> <title>Aspect Ratio Image Preview</title> <style> /* We'll add CSS here next */ </style> </head> <body> <h1>Test Image Aspect Ratios</h1> <input type="file" id="imagePicker" accept="image/*"> <div class="preview-container"> <div class="aspect-ratio-box ratio-1-1"> <img class="preview-image" alt="1:1 Preview"> </div> <div class="aspect-ratio-box ratio-4-3"> <img class="preview-image" alt="4:3 Preview"> </div> <div class="aspect-ratio-box ratio-16-9"> <img class="preview-image" alt="16:9 Preview"> </div> <div class="aspect-ratio-box ratio-9-16"> <img class="preview-image" alt="9:16 Preview"> </div> </div> <script> // JavaScript will go here later </script> </body> </html>
Step 2: CSS for Fixed Aspect Ratios & object-fit: cover
This is where the magic happens for cropping and maintaining ratios. We'll use padding-top to create fixed aspect ratio containers (since padding is calculated based on the container's width), then position the image to fill the container with object-fit: cover:
body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; } .preview-container { display: flex; gap: 20px; margin-top: 30px; flex-wrap: wrap; } .aspect-ratio-box { position: relative; width: 250px; /* Fixed width for consistency */ overflow: hidden; border: 2px solid #ddd; border-radius: 8px; } /* Aspect ratio calculations: height / width * 100% */ .ratio-1-1 { padding-top: 100%; } /* Square */ .ratio-4-3 { padding-top: 75%; } /* 4:3 */ .ratio-16-9 { padding-top: 56.25%; } /* 16:9 */ .ratio-9-16 { padding-top: 177.78%; } /* 9:16 (portrait) */ .preview-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; /* This crops the image to fill the container without stretching */ }
Step 3: JavaScript File API for Local Image Preview
Now we'll add code to handle the file input, read the local image, and update all preview images. No upload required—everything happens in the browser:
const imagePicker = document.getElementById('imagePicker'); const previewImages = document.querySelectorAll('.preview-image'); imagePicker.addEventListener('change', (e) => { const file = e.target.files[0]; if (!file || !file.type.startsWith('image/')) { alert('Please select a valid image file!'); return; } // Use FileReader to convert the local file to a data URL const reader = new FileReader(); reader.onload = (event) => { const imageUrl = event.target.result; // Update all preview images with the selected image previewImages.forEach(img => { img.src = imageUrl; }); }; reader.readAsDataURL(file); });
Let me break this down:
- We listen for when the user selects a file
- We validate that it's an image file to avoid errors
- We use
FileReaderto turn the local file into a base64 data URL (this lets us display the image without uploading it to a server) - We update every preview image's
srcto this data URL, so all aspect ratio previews show the same image cropped correctly
Step 4: Deploy with Google Apps Script
To make this tool accessible anywhere, we'll deploy it as a Google Apps Script web app:
- Go to Google Apps Script and create a new project
- Rename the project (e.g., "Aspect Ratio Image Tester")
- Delete the default
Code.gsfile, then create a new HTML file (click + > HTML) namedIndex - Paste the full combined HTML/CSS/JS code into the
Indexfile (keep the CSS in the<style>tag and JS in the<script>tag as we did earlier) - Create a new
.gsfile namedCodeand add this function:
function doGet() { return HtmlService.createHtmlOutputFromFile('Index') .setTitle('Aspect Ratio Image Tester') .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL); }
- Deploy as a web app:
- Click Deploy > New deployment
- For "Type", select "Web app"
- Set "Execute as" to "Me"
- Set "Who has access" to "Anyone, even anonymous" (adjust if you want restricted access)
- Click Deploy, authorize the permissions, and copy the web app URL
That's it! Now you can access your tool from that URL, upload any local image, and see how it looks cropped to different aspect ratios instantly.
Bonus Tips
- Add more aspect ratios by creating new
.ratio-X-Yclasses with the correctpadding-topvalue - Add a reset button to clear the previews
- Style the file input to make it look nicer (custom buttons instead of the default input)
内容的提问来源于stack exchange,提问作者user7810630

