侧边栏壁纸
博主头像
YOUZI

我依旧在追寻自由的路上

  • 累计撰写 85 篇文章
  • 累计创建 10 个分类
  • 累计创建 27 个标签

目 录CONTENT

文章目录

纯JS弹幕效果

柚子
原创 / 2024-08-04 / 0 评论 / 0 点赞 / 37 阅读 / 0 字
温馨提示:
本文最后更新于35天前,若内容或图片失效,请留言反馈。 部分素材来自网络,若不小心影响您的利益,请联系 站长 删除。

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全屏弹幕</title>
    <style>
        /* 页面主体样式,确保无边距、无内边距、无滚动条,高度为100%,背景色为黑色 */
        body, html {
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100%;
            background-color: black;
        }
        /* 弹幕容器样式,绝对定位,覆盖整个页面,不允许鼠标事件 */
        .danmu-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
        }
        /* 单条弹幕样式,绝对定位,内容不换行,白色字体,24px大小,加粗 */
        .danmu {
            position: absolute;
            white-space: nowrap;
            color: white;
            font-size: 24px;
            font-weight: bold;
        }
    </style>
</head>
<body>
<!-- 弹幕容器元素 -->
<div class="danmu-container" id="danmuContainer"></div>

<script>
    // 获取弹幕容器元素
    const danmuContainer = document.getElementById('danmuContainer');

    /**
     * 创建并添加一条弹幕
     * @param {string} text 弹幕文本内容
     */
    function createDanmu(text) {
        const danmu = document.createElement('div');
        danmu.className = 'danmu';
        danmu.textContent = text;

        // 设置弹幕的位置和初始位置
        const startTop = Math.random() * (window.innerHeight - 30); // 防止弹幕超出窗口
        danmu.style.top = `${startTop}px`;
        danmu.style.left = `${window.innerWidth}px`;

        danmuContainer.appendChild(danmu);

        // 设置弹幕的移动时间
        const duration = 10 + Math.random() * 10; // 弹幕移动时间 10-20 秒

        // 动画效果:从右向左移动到视图外
        danmu.animate([
            { transform: `translateX(-${window.innerWidth + danmu.clientWidth}px)` }
        ], {
            duration: duration * 1000,
            easing: 'linear',
            iterations: 1,
            fill: 'forwards'
        }).onfinish = () => {
            danmuContainer.removeChild(danmu);
        };
    }

    /**
     * 开始发送弹幕
     */
    function startDanmu() {
        // 每隔1秒添加一条弹幕
        setInterval(() => createDanmu('Ciallo~(∠・ω< )⌒★'), 1000);
    }

    // 启动弹幕
    startDanmu();
</script>
</body>
</html>

预览

看这里或者这儿

2024-08-15-wn1j.webp

2024-08-15-DYnC.webp

0

评论区