You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改随机图片放置功能:调用目录所有图片而非单张重复使用

修改方案:调用本地目录全部图片并随机无重叠放置

需求说明

原代码从单一远程源随机重复调用图片,现需修改为加载指定本地目录下的所有图片,每张仅使用一次,同时保持随机无重叠的放置逻辑。


修改后的代码

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机图片展示</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="assets/js/script.js"></script>
</head>
<body>
    <!-- 动态生成图片,无需手动添加占位div -->
</body>
</html>

CSS

* {
  margin:0;
  padding:0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden; /* 防止图片超出视口后出现滚动条 */
}
body {
  margin: 0;
  width: 100%;
  position: relative; /* 确保绝对定位的图片以body为参照 */
}

.random {
  position: absolute;
  width: 128px;
  height: 160px;
}

JavaScript

const imgPositions = [];
let maxX, maxY;
// 1. 定义本地目录的图片列表
// 若图片按顺序命名(如1.png到12.png),可自动生成;若文件名不规律,手动列出即可
const imageList = Array.from({length: 12}, (_, i) => `assets/images/${i+1}.png`);
// 2. 打乱图片列表,实现随机顺序
shuffleArray(imageList);
let currentImgIndex = 0;

function placeImg() {
    // 所有图片已放置完成,停止定时器
    if (currentImgIndex >= imageList.length) {
        clearInterval(window.imgInterval);
        return;
    }

    const imgSrc = imageList[currentImgIndex];
    const { random: r } = Math;  
    const x = r() * maxX;
    const y = r() * maxY;
    
    if (!isOverlap(x, y)) {
        // 创建img元素,比修改innerHTML性能更好
        const img = document.createElement('img');
        img.className = 'random';
        img.style.left = `${x}px`;
        img.style.top = `${y}px`;
        img.src = imgSrc;
        document.body.appendChild(img);
        
        imgPositions.push({x, y});
        currentImgIndex++;
    }
}

// 准确判断矩形是否重叠的逻辑
function isOverlap(newX, newY) {
    const imgWidth = 128;
    const imgHeight = 160;

    for (const pos of imgPositions) {
        // 矩形不重叠的条件:新图片在已有图片的左、右、上、下侧
        const noOverlap = 
            newX + imgWidth < pos.x || 
            newX > pos.x + imgWidth || 
            newY + imgHeight < pos.y || 
            newY > pos.y + imgHeight;
        
        if (!noOverlap) {
            return true; // 存在重叠
        }
    }
    return false;
}

// 数组打乱函数(Fisher-Yates算法)
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

window.onload = function() {
    maxX = window.innerWidth - 128;
    maxY = window.innerHeight - 160;
    // 保存定时器引用,方便后续停止
    window.imgInterval = setInterval(placeImg, 10);
}

window.onresize = function() {
    maxX = window.innerWidth - 128;
    maxY = window.innerHeight - 160;
}

关键修改点

  • 图片来源改为本地目录:通过imageList定义本地图片路径,可根据实际文件名调整。
  • 每张图片仅使用一次:打乱图片列表后按顺序取用,用完即停止定时器。
  • 优化DOM操作:使用createElement创建图片元素,避免频繁修改innerHTML导致的性能问题。
  • 修复重叠判断逻辑:采用更准确的矩形不重叠条件判断,避免误判。
  • 添加数组打乱算法:使用Fisher-Yates算法打乱图片顺序,保证随机展示。

内容的提问来源于stack exchange,提问作者Eli McGehee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:20:31