手写一个转盘抽奖

实现效果 【手写一个转盘抽奖】手写一个转盘抽奖
文章图片
手写一个转盘抽奖
文章图片

html核心代码如下

手写一个转盘抽奖
文章图片

css核心代码如下
.box { width: 400px; height: 400px; border: 1px solid #cccccc; margin: 0 auto; display: flex; align-items: center; justify-content: center; position: relative; }.wrap { width: 300px; height: 300px; border: 1px solid #000; border-radius: 50%; position: relative; overflow: hidden; }.item { position: absolute; border-top: 1px solid red; width: 150px; left: 50%; top: 50%; transform: translate(-0%, -50%); transform-origin: left; right: 0; left: auto; }.point { position: absolute; z-index: 11; }.point img { width: 60px; }.prizeWrap { padding-top: 37px; position: absolute; left: 50%; top: -50%; transform: translate(-50%) rotate(313deg); transform-origin: center; }

js核心代码如下
initPrize('奖品2', function (prizeObj) { alert(`恭喜你抽中${prizeObj.name}`) location.reload() }); /* prizeList:奖品列表 result:抽中的结果 */ function initPrize(result = '奖品4', callbck = function () { }, prizeList = [ { name: '奖品1' }, { name: '奖品2' }, { name: '奖品3' }, { name: '奖品4' }, ]) { const circle = 3//要旋转的圈数 const during = 2//旋转多久2代表2秒 const wrap = document.querySelector('.wrap'); wrap.style = ` transition: all ${during}s` let html = ``; const area = 360 / (prizeList.length) prizeList.forEach((item, index) => { html += `${item.name}` }); wrap.innerHTML = html document.querySelector('.point').addEventListener('click', function (e) { let prizeIndex = 0; //对用结果在奖项列表的index for (let i = 0; i < prizeList.length; i++) { const item = prizeList[i] if (item.name == result) { prizeIndex = i; break; } } let rotate = 360 * circle + ((prizeIndex + 2) * area) + area / 2; const style = wrap.getAttribute('style') const hasRotate = style && style.indexOf('-') != -1 wrap.style.transform = `rotate(${hasRotate ? rotate : -rotate}deg)` setTimeout(function () { callbck(prizeList[prizeIndex]) }, during * 1000) }) }

    推荐阅读