javascript - Chrome canvas 2d context measureText giving me weird results -
here's compact version of problem
let canvas = document.createelement('canvas') let ctx = canvas.getcontext('2d') ctx.font = '11pt calibri' ctx.fillstyle = '#000000' let temp = ctx.font console.log(ctx.font) console.log(ctx.measuretext('m').width) ctx.font = 'bold ' + ctx.font console.log(ctx.font) console.log(ctx.measuretext('m').width) ctx.font = 'italic ' + ctx.font console.log(ctx.font) console.log(ctx.measuretext('m').width) ctx.font = temp console.log(ctx.font) console.log(ctx.measuretext('m').width)
running code in chrome produces incorrect numbers, @ least @ end. first i'm setting font '11pt calibri', chrome changes '15px calibri' reason, , because of it's producing text that's bigger correct. read canvas runs @ 96dpi correct px should 14.6.
after that, i'm measuring width of text m, comes out @ 12.53401184 me, number important.
after that, i've modified font add bold , italic, , roll font was. when measure it, gives me 12.824707, massive 0.3px off. i'm drawing text on canvas anywhere 600px 800px width, , need wrap correctly, need precise 1px on line, individual letters need have @ least 0.02px accuracy, worked decently until started using bolds , italics.
none of above problems exist on firefox, , disabling canvas hardware acceleration on chrome doesn't seem have effect. i'm using chrome 52.0 current latest version.
edit: figured out don't need of incorrect number, doing enough.
let canvas = document.createelement('canvas') let ctx = canvas.getcontext('2d') ctx.font = '11pt calibri' ctx.fillstyle = '#000000' console.log(ctx.font) console.log(ctx.measuretext('m').width) let temp = ctx.font ctx.font = temp console.log(ctx.font) console.log(ctx.measuretext('m').width)
i realized why it's broken. chrome internally compensate pt values, though font gets highjacked 15px. when font value ctx.font modify it, i'm getting modified px value, instead of original pt i'm giving raw 15px value, when happens chrome doesn't compensate. workaround keep original font somewhere else, ctx.originalfont , use modifying instead of ctx.font
for example works
let canvas = document.createelement('canvas') let ctx = canvas.getcontext('2d') ctx.font = '11pt calibri' ctx.originalfont = '11pt calibri' ctx.fillstyle = '#000000' console.log(ctx.font) console.log(ctx.measuretext('m').width) let temp = ctx.originalfont ctx.font = temp console.log(ctx.font) console.log(ctx.measuretext('m').width)
Comments
Post a Comment