如何实现类似Palantir网站的像素化/方块化图片加载动画(仅需转全图效果)
实现方块化图片加载动画(仅保留逐步显现效果)
这种效果的核心是把图片拆分成网格状小方块,通过控制每个方块的显示状态(比如透明度变化、缩放过渡),按节奏完成从方块到完整图片的过渡。下面是纯前端实现方案,无需依赖外部库:
完整代码示例
HTML
<div class="image-container"> <canvas id="pixelCanvas"></canvas> <img id="targetImage" src="your-image.jpg" style="display: none;" alt="目标图片"> </div>
CSS
.image-container { width: 800px; /* 按需调整容器尺寸 */ height: 600px; position: relative; overflow: hidden; } #pixelCanvas { width: 100%; height: 100%; }
JavaScript
const canvas = document.getElementById('pixelCanvas'); const ctx = canvas.getContext('2d'); const img = document.getElementById('targetImage'); // 可自定义的参数 const blockSize = 20; // 方块尺寸,越小效果越细腻 const animationDuration = 1500; // 总动画时长(毫秒) const delayRange = 800; // 方块动画的最大延迟值(控制错落感) // 等待图片加载完成后启动动画 img.onload = function() { canvas.width = img.width; canvas.height = img.height; const cols = Math.ceil(img.width / blockSize); const rows = Math.ceil(img.height / blockSize); // 生成所有方块的坐标与延迟数据 const blocks = []; for (let y = 0; y < rows; y++) { for (let x = 0; x < cols; x++) { blocks.push({ x: x * blockSize, y: y * blockSize, width: Math.min(blockSize, img.width - x * blockSize), height: Math.min(blockSize, img.height - y * blockSize), delay: Math.random() * delayRange }); } } animateBlocks(blocks); }; function animateBlocks(blocks) { const startTime = Date.now(); function updateFrame() { const elapsed = Date.now() - startTime; ctx.clearRect(0, 0, canvas.width, canvas.height); blocks.forEach(block => { // 计算当前方块的动画进度 const progress = Math.max(0, Math.min(1, (elapsed - block.delay) / animationDuration)); if (progress > 0) { // 应用透明度+缩放的过渡效果 ctx.globalAlpha = progress; ctx.save(); ctx.translate(block.x + block.width/2, block.y + block.height/2); ctx.scale(progress, progress); ctx.drawImage( img, block.x, block.y, block.width, block.height, -block.width/2, -block.height/2, block.width, block.height ); ctx.restore(); ctx.globalAlpha = 1; } }); // 动画未结束则持续更新帧 if (elapsed < animationDuration + delayRange) { requestAnimationFrame(updateFrame); } else { // 动画收尾:直接绘制完整图片,避免残留瑕疵 ctx.drawImage(img, 0, 0); } } requestAnimationFrame(updateFrame); }
关键逻辑说明
- 参数调整:修改
blockSize、animationDuration、delayRange可以快速调整效果的细腻度、整体节奏和错落感。 - 方块生成:遍历图片网格区域,为每个方块分配随机延迟,避免同步显示的生硬感。
- 动画控制:通过
requestAnimationFrame逐帧计算进度,同步更新每个方块的透明度和缩放比例,最终平滑过渡到完整图片。 - 替代思路:如果不想用Canvas,也可以用CSS Grid生成网格容器,每个网格项作为方块,通过背景图定位到对应区域,再用CSS动画控制
opacity和transform: scale()属性,但Canvas方案更适配任意尺寸的图片,无需手动计算背景定位。
内容的提问来源于stack exchange,提问作者tea
相关产品推荐
相关产品推荐

