sroxck

sroxck

キャンバスを使用してプロトタイプの扇形ホイールメニューを描画する

ゲーム内では通常、原型の円盤メニューがあり、扇形で構成されています。プロジェクトでは右クリックの円形メニューを使用する必要があるため、以下に canvas を使って描画します。

img

思路#

核心的な考え方は 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

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。