ゲーム内では通常、原型の円盤メニューがあり、扇形で構成されています。プロジェクトでは右クリックの円形メニューを使用する必要があるため、以下に 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