JS+Canvas绘制抽奖转盘
短信预约 -IT技能 免费直播动态提醒
本文实例为大家分享了JS+Canvas绘制抽奖转盘的具体代码,供大家参考,具体内容如下
给大家分享一个Canvas绘制的转盘抽奖,点击开关开始转动时,转盘开始转动,转盘停止时指针指向的区域即为抽中的奖品,并显示在转盘中间,效果图如下:
动画实的代码如下:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
background: #eee;
}
</style>
<title>Canvas绘制抽奖转盘</title>
<script>
window.onload = function () {
var canvas = document.getElementById("canvas");
var cobj = canvas.getContext("2d");
var btn = document.getElementById("btn");
var num = Math.PI / 180;
cobj.translate(250, 250);
var colorArr = ["#24a274", "#2a70a6", "#6d56c3", "#b23880", "#7a9a36", "#b48548", "#397839", "#89489c"];
var textArr = ["js", "html", "css", "php", "mysql", "node", "flutter", "java"];
var angle = 0;
btn.onclick = function () {
location.reload();
};
var step = 10 + 10 * Math.random();
var t = setInterval(function () {
if (step <= 0.3) {
clearInterval(t);
var num1 = Math.ceil(angle / 45);
var con = textArr[textArr.length - num1];
cobj.font = "18px sans-serif";
cobj.textAlign = "center";
cobj.fillText(con, 0, 0);
} else {
if (angle >= 360) {
angle = 0;
}
step *= 0.95;
angle += step;
cobj.clearRect(-200, -200, 500, 500);
cobj.beginPath();
cobj.lineWidth = 5;
cobj.moveTo(135, 0);
cobj.lineTo(150, 0);
cobj.stroke();
cobj.lineWidth = 2;
cobj.save();
cobj.rotate(angle * num);
for (var i = 1; i <= 8; i++) {
cobj.beginPath();
cobj.moveTo(0, 0);
cobj.fillStyle = colorArr[i - 1];
cobj.arc(0, 0, 130, (i - 1) * 45 * num, i * 45 * num);
cobj.closePath();
cobj.stroke();
cobj.fill();
}
cobj.beginPath();
cobj.fillStyle = "#fff";
cobj.arc(0, 0, 60, 0, 2 * Math.PI);
cobj.fill();
for (var i = 0; i < 8; i++) {
cobj.save();
cobj.beginPath();
cobj.rotate((i * 45 + 20) * num);
cobj.fillStyle = "#222";
cobj.font = "18px sans-serif";
cobj.fillText(textArr[i], 75, 0);
cobj.restore();
}
cobj.restore();
}
}, 60)
}
</script>
</head>
<body>
<canvas id="canvas" width=500 height=500></canvas>
<input type="button" value="开始" id="btn" />
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341