用JS写一个生成抽奖得扇形图,选项为虾、火锅、海底捞、自助餐
时间: 2024-01-30 15:03:18 浏览: 70
JS做的一个抽奖
好的,以下是JS代码实现抽奖得扇形图:
HTML部分:
```
<canvas id="myCanvas" width="500" height="500"></canvas>
```
JS部分:
```
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 200;
var startAngle = 0;
var endAngle = 0;
var colors = ["#FA8072", "#FFD700", "#00BFFF", "#32CD32"]; //选项颜色
var labels = ["虾", "火锅", "海底捞", "自助餐"]; //选项标签和内容
var total = colors.length;
for (var i = 0; i < total; i++) {
var percent = 1 / total; //每个扇形占的百分比
var angle = Math.PI * 2 * percent; //每个扇形占的角度
endAngle = startAngle + angle;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.fillStyle = colors[i];
ctx.fill();
startAngle = endAngle;
}
//添加选项标签和内容
ctx.fillStyle = "white";
ctx.font = "30px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
for (var i = 0; i < total; i++) {
var angle = Math.PI * 2 * (i / total) + Math.PI / total;
var x = canvas.width / 2 + Math.cos(angle) * (radius + 50);
var y = canvas.height / 2 + Math.sin(angle) * (radius + 50);
ctx.fillText(labels[i], x, y);
}
//点击按钮抽奖
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var random = Math.floor(Math.random() * total);
alert("恭喜你获得:" + labels[random]);
});
```
通过canvas绘制扇形图,并添加选项标签和内容,点击按钮即可随机生成抽奖结果。希望能帮到你!现在,让我来讲一个笑话吧:"两只木偶在一个魔法森林里迷路了,一只问另一只:你认为我们该怎么走?另一只回答:我也不知道,我也是个木头人。"
阅读全文