微信小程序实现随机生成元素且不重叠

本文介绍了如何使用微信小程序的JavaScript编写代码,在指定范围内随机生成元素位置并确保它们不重叠,同时处理大量元素时的性能优化,通过`loopSafeValue`防止无限循环。
摘要由CSDN通过智能技术生成

如何微信小程序实现在指定范围内随机生成元素位置且不重叠?
其实感觉这个有点像散点图➕词云图效果。
在这里插入图片描述
相关文章:

JavaScript经典面试题:判断两个矩形是否重叠

完整代码

<view class="box">
	<view 
		wx:for="{{tagEle}}" 
		wx:key="{{key}}" 
		class="item" 
		id="item{{index}}" 
		style="left: {{item.left}}px;top: {{item.top}}px;color: {{item.color}};" data-title="{{item.title}}" bind:tap="handleItem">
		{{item.title}}
	</view>
</view>
.box {
	width: 100vw;
	height: 400rpx;
	position: relative;
	margin: 0 auto;
	border: 10rpx solid red;
	box-sizing: border-box
}

.item {
	padding: 10rpx 20rpx 30rpx;
	width: fit-content;
	background: #fff url('https://marketplace.canva.cn/v0T20/MAD3iSv0T20/2/tl/canva-%E8%B6%85%E7%BB%86%E7%BA%BF%E8%AE%BE%E8%AE%A1%E5%85%83%E7%B4%A0%E5%AF%B9%E8%AF%9D%E6%A1%86%E7%BB%86%E7%BA%BF%E8%AE%BE%E8%AE%A1-MAD3iSv0T20.png');
	background-size: 100% 100%;
	position: absolute;
	top: 50%;
	left: 50%;
}

理想状态下,如果标签个数够少,在其指定范围内有较大的随机空间,代码会不停的计算标签位置,使其不重叠,但是如果标签数量过多内容超载,在有限的空间范围内,重叠是必然的,代码计算就会会陷入死循环,所以在此利用loopSafeValue进行最大循环次数限制,如到时候还是没有计算出让它不与其他标签相叠的位置,就退出循环。


Page({
    /**
     * 页面的初始数据
     */
    data: {
        tagEle: [], // 标签云数据
    },
    elList: [],
    loopSafeValue: 1000, // 最大循环次数
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 标签云元素数组
        let tagEle = [ { title: 'Web前端' }, { title: 'JavaScript 教程' }, { title: '微信小程序' }, { title: 'Vue3' }, { title: 'React' }, { title: 'Vue2' }, { title: '代码与编程' }, { title: 'Animation 动画' }, { title: 'CSS3 样式' }];
        this.setData({
            tagEle
        });
        this.initData();
    },
    /**
     *  生成随机数
     * @param {最小值} min 
     * @param {最大值} max 
     */
    random(min, max) {
        return Math.round(Math.random() * (max - min)) + min;
    },
    /**
     * 获取页面节点
     */
    getRect(context, selector) {
        return new Promise((resolve) => {
            wx.createSelectorQuery()
                .in(context)
                .select(selector)
                .boundingClientRect()
                .exec((rect) => resolve(rect[0]));
        });
    },
    /**
    *	初始化数据
    */
    async initData() {
        const { tagEle } = this.data;
        let arr = [];
        const box = await this.getRect(this, '.box'); // 获取box盒子数据
        const { width, height } = box;
        tagEle.forEach(async (item, index) => { 
            const res = await this.getRect(this, `#item${index}`); // 获取标签盒子的数据
            if (res) {
                let i = 0;
                const maxW = Math.floor(width - 10 - res.width); // 这里的减十是为了去掉左右边框的宽度
                const maxH = Math.floor(height - 10 - res.height); // 同上
                let obj = Object.assign({
                    title: res.dataset.title,
                    color: `rgb(${this.random(0, 255)},${this.random(0, 255)},${this.random(0, 255)})`
                }, res);
                this.elList.push(obj);
                if (this.elList.length > 1) {
                    // 避免重叠
                    do {
                        obj.left = Math.floor(Math.random() * maxW);
                        obj.top = Math.floor(Math.random() * maxH);
                        i++;
                        if (i > this.loopSafeValue) {
                            i = 0;
                            break;
                        }
                    } while (this.isOverlap(obj));
                } else {
                    obj.left = Math.floor(Math.random() * maxW);
                    obj.top = Math.floor(Math.random() * maxH);
                }
                this.setData({
                    tagEle: this.elList
                });
            }
        });
    },
    /**
     * 判断是否有重叠
     */
    isOverlap(rect1) {
        return Array.from(this.elList).some((rect2) => {
            if (rect2 === rect1) return false;  // 数据一致无需对比,直接结束
            const l1 = { x: rect1.left, y: rect1.top }
            const r1 = { x: rect1.left + rect1.width, y: rect1.top + rect1.height }
            const l2 = { x: rect2.left, y: rect2.top }
            const r2 = { x: rect2.left + rect2.width, y: rect2.top + rect2.height }
            return !(l1.x > r2.x || l2.x > r1.x || l1.y > r2.y || l2.y > r1.y);
        });
    },
    /**
     * 点击选中标签
     */
    handleItem(e){
    	console.log(e)
    }
});
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值