Last active
August 25, 2020 13:26
-
-
Save iso2022jp/2c3dccc7c9a88fbfca7e441fdc137791 to your computer and use it in GitHub Desktop.
CanvasRenderingContext2D.measureText のテスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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