如何实现图片逐像素裁剪替换动画且不改变尺寸?
固定尺寸图片逐像素切换动画实现方案
需求说明
用带样式的div模拟图片:Photo1(background: blue)代表原图,Photo2(background: red)代表编辑后图片。要求点击「Start」按钮时,原图逐像素裁剪消失,编辑后图片同步显示,全程图片尺寸保持不变,效果类似背景替换动画。现有代码会导致图片尺寸变化,虽了解object-fit但不熟悉用法,需要修复。
原代码
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Page title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <button>Start</button> <div class="Handler"> <div class="Photo1"></div> <div class="Photo2"></div> </div> </body> </html>
CSS
*{ margin: 0; padding: 0; box-sizing: border-box; } .Handler{ position: absolute; top: 50%; left: 50%; width: 80%; height: 400px; display: flex; justify-content: center; transform: translate(-50%, -50%); } .Photo1{ width: 100%; height: 100%; background: blue; transition: 1.5s; } .Photo2{ width: 0; height: 100%; background: red; transition: 1.5s; } button{ width: 60%; border: none; background: blue; color: white; padding: 10px; position: absolute; top: 10%; left: 50%; transform: translate(-50%, -50%); font-size: 18px; font-weight: bold; }
JS
let a = document.querySelector("button"), b = document.querySelector(".Photo1"), c = document.querySelector(".Photo2"); a.addEventListener("click", function(){ b.style.width = "0px"; c.style.width = "100%"; setTimeout(function(){ c.style.width = "0px"; b.style.width = "100%"; }, 3000); });
问题分析
原代码使用flex布局让两张图片并排,修改宽度时会导致图片横向挤压,视觉上尺寸发生变化,不符合固定尺寸的要求。
修复方案
通过绝对定位让两张图片重叠在固定尺寸的容器内,修改上层图片的宽度实现逐像素消失效果,全程保持容器和图片尺寸不变。
修改后的代码
CSS
*{ margin: 0; padding: 0; box-sizing: border-box; } .Handler{ position: absolute; top: 50%; left: 50%; width: 80%; height: 400px; transform: translate(-50%, -50%); position: relative; /* 设置为绝对定位父容器 */ overflow: hidden; /* 防止图片溢出容器 */ } .Photo1{ position: absolute; /* 绝对定位覆盖整个容器 */ top: 0; left: 0; width: 100%; height: 100%; background: blue; transition: width 1.5s linear; /* 明确过渡属性,linear更贴近逐像素效果 */ z-index: 1; /* 确保原图在编辑图上方 */ } .Photo2{ position: absolute; /* 绝对定位与原图重叠 */ top: 0; left: 0; width: 100%; height: 100%; background: red; } button{ width: 60%; border: none; background: blue; color: white; padding: 10px; position: absolute; top: 10%; left: 50%; transform: translate(-50%, -50%); font-size: 18px; font-weight: bold; z-index: 2; /* 确保按钮在最上层 */ }
JS
let a = document.querySelector("button"), b = document.querySelector(".Photo1"); a.addEventListener("click", function(){ b.style.width = "0"; setTimeout(function(){ b.style.width = "100%"; }, 3000); });
补充说明
- 两张图片均通过绝对定位固定在容器内,尺寸与容器完全一致,动画过程中不会改变尺寸。
- 若实际使用
<img>标签,可添加object-fit: cover确保图片按比例填充容器,避免拉伸变形,示例如下:
.Photo1 img, .Photo2 img { width: 100%; height: 100%; object-fit: cover; }
内容的提问来源于stack exchange,提问作者user22324132
相关产品推荐
相关产品推荐

