Canvasでテキストを上下左右中央揃えで配置するサンプル

// <canvas id="canvas"></canvas>
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
const ctxWidth = 300
const ctxHeight = 200

canvas.width = ctxWidth
canvas.height = ctxHeight
canvas.style.background = '#fff'

function ctxFillText(text, fontSize, textX, textY, fontStyle, fontFamily) {
  ctx.font = (
    fontStyle ? fontStyle : 'normal') + ' ' +
    fontSize + 'px ' +
    (fontFamily ? fontFamily : 'sans-serif')
  ctx.fillText(
    text,
    textX === 'center' ?
      (ctxWidth - ctx.measureText(text).width) / 2 :
      textX === 'right' ?
        ctxWidth - ctx.measureText(text).width:
        textX && textX !== 'left' ? textX : 0,
    textY === 'center' ?
      (ctxHeight + fontSize / 2) / 2 :
        textY === 'bottom' ?
          ctxHeight - fontSize / 4 :
          textY && textY !== 'top' ? textY : fontSize
  )
}

// ctxFillText(text, fontSize, textX, textY)
ctxFillText('absolute!', 12, 50, 60)

// 'left', 'top' is default
ctxFillText('left 上', 20)
ctxFillText('left 中', 20, null, 'center')
ctxFillText('left 下', 20, null, 'bottom')

ctxFillText('center 上', 20, 'center', 'top')
ctxFillText('center 中', 20, 'center', 'center')
ctxFillText('center 下', 20, 'center', 'bottom')

ctxFillText('right 上', 20, 'right', 'top')
ctxFillText('right 中', 20, 'right', 'center')
ctxFillText('right 下', 20, 'right', 'bottom')
body {
  background: #eee;
}
#content {
  width: 300px;
  margin: 0 auto;
}

元記事を表示する