uniapp小程序弹幕效果

161 阅读1分钟

html代码部分

<template>
	<view class="info-notify">
		<view class="bullet-container">
			<view class="bj-flex-start bullet-item" v-for="(bullet, index) in bullets" :key="index" :style="{ left: bullet.left + 'px',top: bullet.top + 'px' }">
				<view class="notify-photo bj-flex-center" v-if="bullet.avatarUrl">
					<img class="notify-img" :src="$options.filters.imgFormat(bullet.avatarUrl,175,175)" />
				</view>
				<view class="notify-name">
					{{ bullet.text }}
				</view>
			</view>
		</view>
		<view class="btn" @click="addBullet">
			弹幕
		</view>
	</view>
</template>

js部分

<script>
export default {
	data() {
		return {
			bullets: [],
			moveSpeed: 2,
			maxNumBullets: 16
		}
	},
	mounted() {
		setInterval(() => {
			this.updateBullets()
		}, 20)
	},
	methods: {
		addBullet() {
			if (this.bullets.length >= this.maxNumBullets) {return;}
			let text = 'xxxx已加入'
			// 图片
			let avatarUrl = ''
			const speed = this.moveSpeed
			let getWindowInfo = uni.getWindowInfo()
			const left = getWindowInfo.screenWidth
			// 取随机高度
			const top = Math.floor(Math.random() * (1- 40) ) + 40
			this.bullets.push({ text, avatarUrl, speed, left, top })
		},
		updateBullets() {
			for (let i = 0; i < this.bullets.length; i++) {
				const bullet = this.bullets[i]
				bullet.left -= bullet.speed
				if (bullet.left < -150) {
					this.bullets.splice(i, 1)
					i--
				}
			}
		}
	}
}
</script>

css

<style lang="scss" scoped>
.info-notify{
	.bj-flex-start{
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
	}
	.bullet-container {
		position: absolute;
		top: 0%;
		width: 100%;
		z-index: 9999;
	}
	.notify-photo{
		width: 42rpx;
		height: 42rpx;
		border-radius: 50%;
		background: #fff;
	}
	.notify-img{
		width: 38rpx;
		height: 38rpx;
		border-radius: 50%;
	}
	.bullet-item {
		position: absolute;
		white-space: nowrap;
		padding: 4rpx 24rpx 4rpx 4rpx;
		background: rgba(0,0,0,0.6);
		border-radius: 50rpx;
		font-size: 26rpx;
		color: #fff;
	}
	.notify-name{
		padding-left: 16rpx;
	}
	.btn{
		margin-top: 200px;
		background-color: #2196f3;
		color: #fff;
		padding: 10px 20px;
		border-radius: 5px;
		border: none;
		font-size: 14px;
	}
}
</style>

2110bbd3ef8cf43512487d2e25bbd26.png