在游戏里通常会有原型轮盘菜单,由一个个扇形组成,刚好项目中需要使用右键圆形菜单,下面用 canvas 来绘制一个
思路#
核心思路就是 2π /num
num 是你菜单的数量 2π/num 就可以得到一个扇形的弧度
实现#
// 获取Canvas元素和绘图上下文
const canvas = document.getElementById('myCanvas')
const ctx = canvas.getContext('2d')
// 定义圆心和半径
const centerX = canvas.width / 2 // 中心X坐标
const centerY = canvas.height / 2 // 中心Y坐标
const outerRadius = 200 // 外圈半径
const innerRadius = 100 // 内圈半径
// 扇形数量
const outerNumSlices = 12 // 外圈扇形数量
const innerNumSlices = 4 // 内圈扇形数量
// 计算每个扇形的角度(弧度)
const outerSliceAngle = (2 * Math.PI) / outerNumSlices
const innerSliceAngle = (2 * Math.PI) / innerNumSlices
// 绘制扇形 需要参数是 菜单数量 单个菜单的弧度 圆的半径 文本
function draw(num, angle, radius, labels) {
// 循环菜单的数量
for (let i = 0; i < num; i++) {
const startAngle = i * angle //开始的角度
const endAngle = (i + 1) * angle // 结束的角度
// 设置不同的填充颜色(可选)
ctx.fillStyle = `hsl(${(i * 360) / num}, 100%, 50%)`
// 绘制扇形
ctx.beginPath()
ctx.moveTo(centerX, centerY) // 移动到圆心
ctx.arc(centerX, centerY, radius, startAngle, endAngle) // 绘制弧形
ctx.closePath()
ctx.fill() // 填充扇形
// 可选:绘制扇形的边框
ctx.lineWidth = 2 // 设置边框宽度
ctx.strokeStyle = '#000000' // 设置边框颜色
ctx.stroke() // 绘制边框
// 计算文本位置
const midAngle = (startAngle + endAngle) / 2
const textX = centerX + (radius / 1.4) * Math.cos(midAngle)
const textY = centerY + (radius / 1.2) * Math.sin(midAngle)
// 绘制文本
ctx.fillStyle = '#000000'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(labels[i], textX, textY)
}
}
const outerLabels = Array.from({ length: outerNumSlices }, (_, i) => `Outer ${i + 1}`)
const innerLabels = Array.from({ length: innerNumSlices }, (_, i) => `Inner ${i + 1}`)
draw(outerNumSlices, outerSliceAngle, outerRadius, outerLabels)
draw(innerNumSlices, innerSliceAngle, innerRadius, innerLabels)
此文由 Mix Space 同步更新至 xLog
原始链接为 http://www.sroxck.top/posts/fontend/canvas