Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@iso2022jp
Last active August 25, 2020 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iso2022jp/2c3dccc7c9a88fbfca7e441fdc137791 to your computer and use it in GitHub Desktop.
Save iso2022jp/2c3dccc7c9a88fbfca7e441fdc137791 to your computer and use it in GitHub Desktop.
CanvasRenderingContext2D.measureText のテスト
document.addEventListener('DOMContentLoaded', _ => {
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
context.font = '300px "Yu Mincho"'
context.fillStyle = 'white'
context.fillRect(0, 0, canvas.width, canvas.height)
context.textBaseline = 'top'
const preview = (text, x, y) => {
context.fillStyle = 'black'
context.fillText(text, x, y)
const measure = context.measureText(text)
console.log(`width: ${measure.width}`)
console.log(`height: ${measure.actualBoundingBoxAscent + measure.actualBoundingBoxDescent}`)
console.log(`actualBoundingBoxLeft: ${measure.actualBoundingBoxLeft}`)
console.log(`actualBoundingBoxRight: ${measure.actualBoundingBoxRight}`)
console.log(`fontBoundingBoxAscent: ${measure.fontBoundingBoxAscent}`)
console.log(`fontBoundingBoxDescent: ${measure.fontBoundingBoxDescent}`)
console.log(`actualBoundingBoxAscent: ${measure.actualBoundingBoxAscent}`)
console.log(`actualBoundingBoxDescent: ${measure.actualBoundingBoxDescent}`)
console.log(`emHeightAscent: ${measure.emHeightAscent}`)
console.log(`emHeightDescent: ${measure.emHeightDescent}`)
console.log(`hangingBaseline: ${measure.hangingBaseline}`)
console.log(`alphabeticBaseline: ${measure.alphabeticBaseline}`)
console.log(`ideographicBaseline: ${measure.ideographicBaseline}`)
console.log('')
context.strokeStyle = 'blue'
context.strokeRect(
x,
y,
measure.width,
300
)
context.strokeStyle = 'green'
context.moveTo(x, y)
context.lineTo(x + measure.width, y)
context.stroke()
context.strokeStyle = 'red'
context.strokeRect(
x - measure.actualBoundingBoxLeft,
y - measure.actualBoundingBoxAscent,
measure.actualBoundingBoxLeft + measure.actualBoundingBoxRight,
measure.actualBoundingBoxAscent + measure.actualBoundingBoxDescent
)
return measure.width
}
let x = 50
context.font = '900 300px "Yu Gothic"'
x += preview('黼', x, 50)
x += preview('驪', x, 50)
x = 50
//context.font = '900 300px "Yu Mincho"'
x += preview('韆', x, 350)
x += preview('鬮', x, 350)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment