(精华)2020年6月28日 Canvas 抽奖轮盘
程序员文章站
2022-04-10 17:04:35
...
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>转盘旋转的测试</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="border: 1px solid black"></canvas>
<button id="start">开始</button>
<script>
var angle = 0; //旋转角度
var duration = 10000; // 旋转时长为 10 秒
var last = 0; //已旋转时长
var speed = 0; // 旋转速度
var flag = 0; //所有图片是否绘制完毕
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var start = document.getElementById("start");
//移动原始的坐标点
context.translate(canvas.width / 2, canvas.height / 2);
//工厂模式
function loadImg(imgSrc) {
var imgPin = new Image();
imgPin.src = imgSrc;
imgPin.onload = function () {
flag += 1;
if (flag == 2) {
//所有图片加载完
// 需要绘制图片
paintImg();
}
}
return imgPin;
}
var panImg = loadImg('./imgs/pan.png');
var pinImg = loadImg('./imgs/pin.png');
function paintImg(angle) {
var angle = angle ? angle : 0;
context.rotate(angle * Math.PI / 180);
context.drawImage(panImg, -panImg.width / 2, -panImg.height / 2);
context.rotate(-angle * Math.PI / 180);
context.drawImage(pinImg, -pinImg.width / 2, -pinImg.height / 2);
}
start.onclick = function () {
//打断让用户抽到什么奖, 5圈,然后加上对应奖品的弧度,每个奖对应30度
// 12 个
//开始接口
// 随机
last = 0
speed = 0;
var n = Math.round(Math.random() * 12); //2
var angleEnd = 360 * 5 + 30 * n; //
console.log(n)
console.log(angleEnd)
var timer = setInterval(function () {
last += 50;
if (last < duration / 2) {
//速度增加,前5秒
speed += 0.1;
angle += speed;
} else if (last > duration / 2) {
//5秒后,减速运动
if (speed > 5) {
speed -= 0.1;
}
angle += speed;
}
if (angle >= angleEnd) {
//停止旋转
clearInterval(timer);
}
paintImg(angle);
}, 50);
}
</script>
</body>
</html>
附件