当前位置:首页 > JavaScript

js抽奖实现

2026-01-31 16:02:54JavaScript

实现基本的随机抽奖功能

使用JavaScript的Math.random()方法可以快速实现一个简单的随机抽奖。这种方法适用于不需要复杂逻辑的基础抽奖场景。

const participants = ['张三', '李四', '王五', '赵六'];
const winner = participants[Math.floor(Math.random() * participants.length)];
console.log('中奖者:', winner);

权重抽奖实现

对于需要根据不同概率抽奖的场景,可以通过为每个参与者分配权重值来实现。权重越高,中奖概率越大。

const weightedParticipants = [
  { name: '张三', weight: 10 },
  { name: '李四', weight: 30 },
  { name: '王五', weight: 60 }
];

function weightedRandom(items) {
  const totalWeight = items.reduce((sum, item) => sum + item.weight, 0);
  const random = Math.random() * totalWeight;
  let currentWeight = 0;

  for (const item of items) {
    currentWeight += item.weight;
    if (random <= currentWeight) return item;
  }
}

const winner = weightedRandom(weightedParticipants);
console.log('权重抽奖结果:', winner.name);

排除已中奖者的抽奖

在多轮抽奖中,需要确保已中奖者不会重复中奖。可以通过从参与者数组中移除已中奖者来实现。

js抽奖实现

let participants = ['张三', '李四', '王五', '赵六'];
const winners = [];

function drawWinner() {
  if (participants.length === 0) return null;

  const winnerIndex = Math.floor(Math.random() * participants.length);
  const winner = participants[winnerIndex];

  participants = participants.filter((_, index) => index !== winnerIndex);
  winners.push(winner);

  return winner;
}

console.log('第一轮中奖者:', drawWinner());
console.log('第二轮中奖者:', drawWinner());
console.log('剩余参与者:', participants);

可视化抽奖动画效果

为增强用户体验,可以添加抽奖动画效果,模拟转盘滚动逐渐停下的过程。

function drawWithAnimation(elementId, items, duration = 3000) {
  const element = document.getElementById(elementId);
  let startTime = null;
  const totalItems = items.length;

  function animate(timestamp) {
    if (!startTime) startTime = timestamp;
    const elapsed = timestamp - startTime;
    const progress = Math.min(elapsed / duration, 1);

    // 减速效果
    const easedProgress = 1 - Math.pow(1 - progress, 3);
    const currentIndex = Math.floor(easedProgress * totalItems * 10) % totalItems;

    element.textContent = items[currentIndex];

    if (progress < 1) {
      requestAnimationFrame(animate);
    } else {
      const finalIndex = Math.floor(Math.random() * totalItems);
      element.textContent = items[finalIndex];
      console.log('最终中奖者:', items[finalIndex]);
    }
  }

  requestAnimationFrame(animate);
}

// 使用示例
drawWithAnimation('prizeDisplay', ['一等奖', '二等奖', '三等奖', '谢谢参与']);

九宫格抽奖实现

九宫格抽奖是常见的互动形式,可以通过CSS和JavaScript结合实现。

js抽奖实现

<div class="grid-container">
  <div class="grid-item" data-index="0">1</div>
  <div class="grid-item" data-index="1">2</div>
  <div class="grid-item" data-index="2">3</div>
  <div class="grid-item" data-index="7">8</div>
  <div class="grid-item" data-index="8">开始</div>
  <div class="grid-item" data-index="3">4</div>
  <div class="grid-item" data-index="6">7</div>
  <div class="grid-item" data-index="5">6</div>
  <div class="grid-item" data-index="4">5</div>
</div>
const gridItems = document.querySelectorAll('.grid-item');
let isDrawing = false;
let currentIndex = 0;
let speed = 100;
let timer = null;
const prizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6', '奖品7', '奖品8'];

function startDraw() {
  if (isDrawing) return;

  isDrawing = true;
  gridItems.forEach(item => item.classList.remove('active'));

  timer = setInterval(() => {
    gridItems[currentIndex].classList.remove('active');
    currentIndex = (currentIndex + 1) % 8;
    gridItems[currentIndex].classList.add('active');
  }, speed);

  // 3秒后停止
  setTimeout(() => {
    clearInterval(timer);
    isDrawing = false;
    const winnerIndex = Math.floor(Math.random() * 8);
    console.log('中奖奖品:', prizes[winnerIndex]);
  }, 3000);
}

document.querySelector('[data-index="8"]').addEventListener('click', startDraw);

大转盘抽奖实现

大转盘抽奖需要结合CSS旋转动画和JavaScript控制。

function startWheel(selector, items, duration = 5000) {
  const wheel = document.querySelector(selector);
  const anglePerItem = 360 / items.length;
  const targetRotation = 360 * 5 + anglePerItem * Math.floor(Math.random() * items.length);

  wheel.style.transition = `transform ${duration}ms cubic-bezier(0.17, 0.67, 0.21, 0.99)`;
  wheel.style.transform = `rotate(${-targetRotation}deg)`;

  setTimeout(() => {
    const normalizedRotation = targetRotation % 360;
    const winnerIndex = Math.floor((360 - normalizedRotation) / anglePerItem) % items.length;
    console.log('转盘中奖:', items[winnerIndex]);
  }, duration);
}

// 使用示例
startWheel('.wheel', ['一等奖', '二等奖', '三等奖', '谢谢参与']);

抽奖结果统计分析

对于需要记录和分析抽奖结果的场景,可以添加统计功能。

const prizeRecords = [];

function recordPrize(winner, prize) {
  const record = {
    winner,
    prize,
    timestamp: new Date().toISOString()
  };
  prizeRecords.push(record);
  return record;
}

function getPrizeStats() {
  const stats = {};

  prizeRecords.forEach(record => {
    if (!stats[record.prize]) {
      stats[record.prize] = 0;
    }
    stats[record.prize]++;
  });

  return stats;
}

// 使用示例
recordPrize('张三', '一等奖');
recordPrize('李四', '二等奖');
console.log('抽奖统计:', getPrizeStats());

标签: js
分享给朋友:

相关文章

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-contain…

js实现列表

js实现列表

使用 JavaScript 实现列表 JavaScript 提供了多种方式来实现列表功能,包括数组操作、DOM 元素动态生成等。以下是几种常见的实现方法: 使用数组存储列表数据 数组是 JavaS…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现自举

js实现自举

实现 JavaScript 自举的方法 JavaScript 自举(Bootstrap)通常指通过 JavaScript 动态加载自身或依赖的脚本,实现运行时环境的初始化或扩展。以下是几种常见实现方式…

利用js实现

利用js实现

使用 JavaScript 实现 在 JavaScript 中,可以通过多种方式实现功能,具体取决于需求。以下是几种常见的方法: 方法一:使用原生 JavaScript // 示例代码…