sroxck

sroxck

Use canvas to draw a prototype fan-shaped roulette menu

In the game, there is usually a prototype radial menu composed of sectors. The project requires the use of a right-click circular menu, which is drawn using canvas below.

img

Idea#

The core idea is 2π / num

num is the number of items in your menu, and 2π/num gives you the angle of a sector.

Implementation#

// Get the Canvas element and drawing context 
const canvas = document.getElementById('myCanvas')
const ctx = canvas.getContext('2d')

// Define the center and radius
const centerX = canvas.width / 2 // Center X coordinate
const centerY = canvas.height / 2 // Center Y coordinate
const outerRadius = 200 // Outer circle radius
const innerRadius = 100 // Inner circle radius

// Number of sectors
const outerNumSlices = 12 // Number of outer sectors
const innerNumSlices = 4 // Number of inner sectors

// Calculate the angle (in radians) for each sector
const outerSliceAngle = (2 * Math.PI) / outerNumSlices
const innerSliceAngle = (2 * Math.PI) / innerNumSlices

// Draw sectors, parameters are number of menu items, angle of a single menu item, radius of the circle, text
function draw(num, angle, radius, labels) {
  // Loop through the number of menu items
  for (let i = 0; i < num; i++) {
    const startAngle = i * angle  // Starting angle
    const endAngle = (i + 1) * angle // Ending angle

    // Set different fill colors (optional)
    ctx.fillStyle = `hsl(${(i * 360) / num}, 100%, 50%)`

    // Draw sector
    ctx.beginPath()
    ctx.moveTo(centerX, centerY) // Move to center
    ctx.arc(centerX, centerY, radius, startAngle, endAngle) // Draw arc
    ctx.closePath()
    ctx.fill() // Fill sector

    // Optional: Draw sector border
    ctx.lineWidth = 2 // Set border width
    ctx.strokeStyle = '#000000' // Set border color
    ctx.stroke() // Draw border

    // Calculate text position
    const midAngle = (startAngle + endAngle) / 2
    const textX = centerX + (radius / 1.4) * Math.cos(midAngle)
    const textY = centerY + (radius / 1.2) * Math.sin(midAngle)

    // Draw text
    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)

This article is synchronized and updated to xLog by Mix Space. The original link is http://www.sroxck.top/posts/fontend/canvas

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.