我正在使用Canvas 2d上下文计算文本的宽度
例如: canvas2DContext.measureText('Sivakumar Tadisetti')
我正在将字体用作bold 15px "Open Sans", serif
问题:有时measureText()
给出119.4835
,有时给出115.3423
作为宽度。
为什么我得到不同的宽度。我在这里做错了什么?请从下面找到代码段。
var canvas = document.createElement('canvas');
var canvas2DContext = canvas.getContext('2d');
var textWidth = canvas2DContext.measureText("Sivakumar Tadisetti").width;
答案 0 :(得分:2)
有点盲目,但是对我来说,这听起来好像您没有正确等待字体加载:
const ctx = canvas.getContext('2d');
ctx.font = 'bold 15px "Open Sans", serif'
const before_load = ctx.measureText("Sivakumar Tadisetti").width;
console.log('before', before_load);
// load the font
document.fonts.ready
.then(() => {
ctx.font = 'bold 15px "Open Sans", serif'
const after_load = ctx.measureText("Sivakumar Tadisetti").width;
console.log('after', after_load);
});
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<canvas id="canvas"></canvas>
为避免这种情况,您可以在document.fonts.ready
Promise的回调中执行代码:
document.fonts.ready.then(startYourCode);
document.fonts.ready.then(() => {
const ctx = canvas.getContext('2d');
ctx.font = 'bold 15px "Open Sans", serif'
const textWidth= ctx.measureText("Sivakumar Tadisetti").width;
console.log(textWidth);
});
#canvas { font-family: "Open Sans"; }
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<canvas id="canvas"></canvas>