网络上已经有了很多转盘抽奖的代码,但大多是用jQuery插件实现的,其中的原理比较难弄明白,于是自己摸索了一个。最终效果如下:

 
 

// = totalTime) {
stopRotation();
return;
}

var currentAngle = finalValue - easeOut(currentTime,0,finalValue,totalTime);

//弧度随时间递增,但增速由快变慢
startAngle += currentAngle * PI / 180;
draw();

t = setTimeout(rotation, 17);
}

function stopRotation() {
clearTimeout(t);

var arc = startAngle + PI / 2,
index = lenPrize - 1 - ((arc % (2 * PI) / piece) >> 0);

result.innerHTML = '' + prizeList[index] + '';
}
draw();

var run = document.getElementById('run'),
result = document.getElementById('result');
run.onclick = function() {
currentTime = 0;
totalTime = Math.random() * 500 + 4000;
finalValue = Math.random() * 20 + 20;
rotation();
};

function easeOut(t,b,c,d) {
return -c *(t/=d)*(t-2) + b;
}

})();
// ]]>

实现步骤:

1.根据奖品数量绘制转盘

var      r1 = 200,    //外圆半径
r2 = 160, //奖品文字距离圆心的位置
r3 = 60, //中心按钮半径
centerX = c.width / 2, //中点
centerY = c.height / 2,
PI = Math.PI,
prizeList = ['一等奖','二等奖','三等奖','四等奖','五等奖','六等奖','七等奖','八等奖'], //奖品列表
colorList = ['#ffffff','#FDFAC3','#ffffff','#FDFAC3','#ffffff','#FDFAC3','#ffffff','#FDFAC3'], //奖品对应的背景颜色
lenPrize = prizeList.length,
startAngle = 0, //开始绘制时的起始角度
piece = 2 * PI / lenPrize; //根据奖品数量划分区域,单位为弧度
//绘制分区
for (var i = 0; i < lenPrize; i++) {
ctx.fillStyle = colorList[i];
var angle = startAngle + piece * i;
ctx.beginPath();
//设置圆心为起点,方便closePath()自动闭合路径
ctx.moveTo(centerX, centerY);
//分块绘制,目的是方便填充颜色,如果以lineTo的形式绘制,在填充颜色时会很麻烦
ctx.arc(centerX, centerY, r1, angle, angle + piece, false);
ctx.closePath();
ctx.fill();
ctx.stroke(); //绘制奖品说明
ctx.save();
ctx.font = '30px Microsoft YaHei';
ctx.fillStyle = '#d60000';
ctx.translate(centerX + Math.cos(angle + piece / 2) * r2, centerY + Math.sin(angle + piece / 2) * r2);
ctx.rotate(angle + piece / 2 + PI / 2); var s = prizeList[i].split('');
for (var j = 0; j < s.length; j++) {
var text = s[j];
ctx.fillText(text, -ctx.measureText(text).width / 2, 32 * j);
}
ctx.restore();
}

这一部分代码的效果如下:

图一

要注意首个奖品说明的位置,也就是一等奖的位置,是从三点钟方向开始的,这是arc()方法的规定,下面这张图表示从1到N按顺序绘制。

图二

接下来绘制箭头和中心圆:

//绘制箭头
ctx.strokeStyle = '#FF5722';
ctx.fillStyle = '#FF5722';
ctx.save();
ctx.translate(centerX, centerY - 40);
ctx.moveTo( - 10, 0);
ctx.beginPath();
ctx.lineTo( - 10, 0);
ctx.lineTo( - 10, -30);
ctx.lineTo( - 20, -30);
ctx.lineTo(0, -50);
ctx.lineTo(20, -30);
ctx.lineTo(10, -30);
ctx.lineTo(10, 0);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore(); //绘制中心圆
ctx.fillStyle = '#FF5722';
ctx.beginPath();
ctx.arc(centerX, centerY, r3, 0, 2 * PI, false);
ctx.closePath();
ctx.fill();
ctx.stroke(); //绘制抽奖文字
ctx.font = '30px Microsoft YaHei';
ctx.fillStyle = '#fff';
ctx.save();
ctx.translate(centerX, centerY);
ctx.fillText("抽奖", -ctx.measureText(text).width, 10);
ctx.restore();

这就是最终效果

最后实现转盘的转动,先定义几个变量:

var currentTime = 0,  //表示动画开始到现在持续的时间
totalTime = Math.random() * 500 + 4000, //动画总时间
    finalValue = Math.random() * 20 + 20,//动画总时间内期望的位移总量,越大转得越快,因为总时间一定,只有加快速度才能在规定时间内到达期望位移 

   t; //setTimeout Id

转盘转动方法:

function rotation() {
currentTime += 30; //每帧增加30的运行时间
if (currentTime >= totalTime) {//到达总时间后停止动画
stopRotation();
return;
}
//缓动
var currentAngle = finalValue - easeOut(currentTime, 0, finalValue, totalTime); //弧度随时间递增,但增速由快变慢
startAngle += currentAngle * PI / 180; //根据startAngle的变化重新绘制转盘,以达到转动的效果
draw(); t = setTimeout(rotation, 17);
}

停止转盘:

function stopRotation() {
clearTimeout(t);
//动画时间内转动的总弧度,因为是从三点钟方向开始绘制的,所以应当加上PI/2
var arc = startAngle + PI / 2,
//arc模2*PI以计算转动整圈以外不满一圈的零数
//零数除以单位弧度,表示转动了几个单位,不满整数则向下取整(Math.floor)
//奖品数量(以下标算,故先减1)减去转动过的单位得到当前指针所指奖品的索引
index = lenPrize - 1 - ((arc % (2 * PI) / piece) >> 0); result.innerHTML = '<strong style="font-size:26px; color:#f00">' + prizeList[index] + '</strong>';
}

全部代码:

 < !DOCTYPE html >
<html lang = "en" >
<head >
<meta charset = "UTF-8" >
<title> Document </title>
<style>
body{margin: 0; font:12px Arial; background-color: #fff}
.canvas_container{
position: relative;
width: 500px;
height: 500px;
}
#run{
position: absolute;
width: 120px;
height: 120px;
cursor: pointer;
left: 190px;
top: 190px;
}
</style > </head>
<body>
<div class="canvas_container">
<div id="run"></div > <canvas id = "c"width = "500"height = "500" > </canvas>
</div > <div id = "result" > </div> <script>
var c = document.getElementById('c'),
ctx = c.getContext("2d"),
r1 = 200, / / 外圆半径r2 = 160,
//文字所在位置半径
r3 = 60,
//中心按钮
centerX = c.width / 2,
//中点
centerY = c.height / 2,
PI = Math.PI; var prizeList = ['一等奖', '二等奖', '三等奖', '四等奖', '五等奖', '六等奖', '七等奖', '八等奖'],
colorList = ['#ffffff', '#FDFAC3', '#ffffff', '#FDFAC3', '#ffffff', '#FDFAC3', '#ffffff', '#FDFAC3'],
lenPrize = prizeList.length,
lenColor = colorList.length,
piece = 2 * PI / lenPrize,
//根据奖品数量划分区域,单位弧度
startAngle = 0; //起始角度
function draw() {
ctx.clearRect(0, 0, c.width, c.height); ctx.lineWidth = 0.5;
ctx.strokeStyle = '#AF4760'; //绘制分区
for (var i = 0; i < lenPrize; i++) {
ctx.fillStyle = colorList[i];
var angle = startAngle + piece * i;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
//分块绘制,目的是方便填充颜色,如果以lineTo的形式绘制,在填充颜色时会很麻烦
ctx.arc(centerX, centerY, r1, angle, angle + piece, false);
ctx.closePath();
ctx.fill();
ctx.stroke(); //绘制奖品说明
ctx.save();
ctx.font = '30px Microsoft YaHei';
ctx.fillStyle = '#d60000';
ctx.translate(centerX + Math.cos(angle + piece / 2) * r2, centerY + Math.sin(angle + piece / 2) * r2);
ctx.rotate(angle + piece / 2 + PI / 2); var s = prizeList[i].split('');
for (var j = 0; j < s.length; j++) {
var text = s[j];
ctx.fillText(text, -ctx.measureText(text).width / 2, 32 * j);
}
ctx.restore();
} //绘制箭头
ctx.strokeStyle = '#FF5722';
ctx.fillStyle = '#FF5722';
ctx.save();
ctx.translate(centerX, centerY - 40);
ctx.moveTo( - 10, 0);
ctx.beginPath();
ctx.lineTo( - 10, 0);
ctx.lineTo( - 10, -30);
ctx.lineTo( - 20, -30);
ctx.lineTo(0, -50);
ctx.lineTo(20, -30);
ctx.lineTo(10, -30);
ctx.lineTo(10, 0);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore(); //绘制中心圆
ctx.fillStyle = '#FF5722';
ctx.beginPath();
ctx.arc(centerX, centerY, r3, 0, 2 * PI, false);
ctx.closePath();
ctx.fill();
ctx.stroke(); //绘制抽奖文字
ctx.font = '30px Microsoft YaHei';
ctx.fillStyle = '#fff';
ctx.save();
ctx.translate(centerX, centerY);
ctx.fillText("抽奖", -ctx.measureText(text).width, 10);
ctx.restore(); } var currentTime = 0,
totalTime = Math.random() * 500 + 4000,
finalValue = Math.random() * 20 + 20,
//终点值
t; function rotation() {
currentTime += 30;
if (currentTime >= totalTime) {
stopRotation();
return;
} var currentAngle = finalValue - easeOut(currentTime, 0, finalValue, totalTime); //弧度随时间递增,但增速由快变慢
startAngle += currentAngle * PI / 180;
draw(); t = setTimeout(rotation, 17);
} function stopRotation() {
clearTimeout(t); var arc = startAngle + PI / 2,
index = lenPrize - 1 - ((arc % (2 * PI) / piece) >> 0); result.innerHTML = '<strong style="font-size:26px; color:#f00">' + prizeList[index] + '</strong>';
}
draw();
//rotation();
var run = document.getElementById('run'),
result = document.getElementById('result');
run.onclick = function() {
currentTime = 0;
totalTime = Math.random() * 500 + 4000;
finalValue = Math.random() * 20 + 20;
rotation();
}; /*
t: current time(当前时间)
b: beginning value(初始值)
c: change in value(变化总量)
d: duration(持续时间)
*/
function easeOut(t, b, c, d) {
return - c * (t /= d) * (t - 2) + b;
} </script>
</body >
</html>

最新文章

  1. Android 利用内容观察者实现短信窃听
  2. 【BZOJ-1218】激光炸弹 前缀和 + 枚举
  3. Xcode的command+shift+o是一个不错的工具
  4. Corel Painter 15在Surface Pro 4下开启笔触压力感应
  5. RecyclerView解析--onViewDetachedFromWindow()/onViewAttachedToWindow()
  6. java8新特性笔记
  7. C++ 中字符串标准输入的学习及实验
  8. [求助]谁能给我讲解一下,iOS编程要如何实时显示采集到的图像???
  9. 【BZOJ3110】【整体二分+树状数组区间修改/线段树】K大数查询
  10. WebGL自学教程——WebGL演示样例:開始
  11. jquery简单封装
  12. wpf 遍历listview 时 传入指定类型 得到指定类型控件info
  13. PHP运行模式(cgi,fast-cgi,cli, ISAPI ,web模块模式)【转载】
  14. Java学习笔记四---打包成双击可运行的jar文件
  15. Scrapy 1.4 文档 03 Scrapy 教程
  16. Spring Cloud 2-Hystrix DashBoard仪表盘(五)
  17. Linux 驱动——Button驱动3(poll机制)
  18. Taskctl安装及配置Kettle插件
  19. Python——Entry、Text控件
  20. centos 7.x开放端口

热门文章

  1. POJ3071 Football 【概率dp】
  2. 刷题总结——book of evil(codefoeces 337D)
  3. Keepalived+NFS+SHELL脚本实现NFS-HA高可用
  4. 過充保護警告訊息 over charging protection,Battery over voltage protection, warning message
  5. Linux 之 xunsearch
  6. AC日记——dispatching bzoj 2809
  7. IOS-&lt;input&gt;表单元素只能读,设置readonly时光标仍然可见的解决办
  8. win10下Vmware12虚拟机安装Ubuntu16.04
  9. 洛谷—— P2251 质量检测
  10. PyTorch学习笔记之DataLoaders