如何用JavaScript判断页面中两个已加载WEBP图片是否相等(无AJAX)
Great question! You don’t even need an external JavaScript library for this—we can use the browser’s built-in Canvas API to compare the pixel data of the two images directly. Here’s a practical, step-by-step approach with code:
Core Idea
We’ll load both images into the browser, draw each onto a hidden canvas, extract their raw pixel data, then compare those pixel arrays to check if the images are identical. No server requests required.
Step 1: Load Images Asynchronously
First, we need to ensure both images are fully loaded before processing. Let’s wrap image loading in a promise for clean async handling:
function loadImage(src) { return new Promise((resolve, reject) => { const img = new Image(); // Handle cross-origin images (requires server to send CORS headers) img.crossOrigin = 'anonymous'; img.onload = () => resolve(img); img.onerror = reject; img.src = src; }); }
Step 2: Compare Pixel Data
Once both images are loaded, we’ll first do a quick dimension check (if width/height don’t match, they’re definitely not equal). Then we’ll draw each image to a canvas, extract pixel data, and compare the arrays efficiently.
async function areImagesEqual(imgSrc1, imgSrc2) { try { // Load both images in parallel const [img1, img2] = await Promise.all([loadImage(imgSrc1), loadImage(imgSrc2)]); // Quick exit if dimensions don't match if (img1.width !== img2.width || img1.height !== img2.height) { return false; } // Create a reusable canvas element const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = img1.width; canvas.height = img1.height; // Draw first image and get pixel data ctx.drawImage(img1, 0, 0); const data1 = ctx.getImageData(0, 0, canvas.width, canvas.height).data; // Clear canvas and draw second image ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img2, 0, 0); const data2 = ctx.getImageData(0, 0, canvas.width, canvas.height).data; // Optimize comparison: convert to Uint32Array (compare 4 bytes per pixel at once) const uint32Data1 = new Uint32Array(data1.buffer); const uint32Data2 = new Uint32Array(data2.buffer); // Loop through pixels and compare for (let i = 0; i < uint32Data1.length; i++) { if (uint32Data1[i] !== uint32Data2[i]) { return false; } } return true; } catch (error) { console.error('Error comparing images:', error); return false; } }
Step 3: Use the Function
Call this function with your two WEBP image sources like so:
areImagesEqual('path/to/first-image.webp', 'path/to/second-image.webp') .then(areEqual => { console.log('Images are identical:', areEqual); // Add your logic here (e.g., show a message, update UI) });
Key Notes
- CORS Considerations: If your images are hosted on a different domain, the server must send
Access-Control-Allow-Originheaders. Otherwise, the browser will block access to canvas pixel data (a "tainted canvas"). - Performance: Using
Uint32Arrayspeeds up comparison by checking one 32-bit integer (representing a full RGBA pixel) at a time instead of 4 separate byte checks. - Transparency: This method accounts for alpha channels, so images with different transparency levels will be marked as unequal.
内容的提问来源于stack exchange,提问作者Juliyanage Silva

