gpt4 book ai didi

html Canvas 文本大小不准确

转载 作者:可可西里 更新时间:2023-11-01 12:53:22 24 4
gpt4 key购买 nike

我试图将文本居中放置在一个框中,但 ctx.measureText() 没有返回准确的值。运行以下代码时,文本未准确居中。它在谷歌浏览器下为我运行,但我无法让它在 jsfiddle 下运行(抱歉)

<html>
<head>
<script type="text/javascript">
function writeText(){
canvas=document.getElementById('canvas');
ctx = canvas.getContext('2d');
ctx.fillStyle='rgb(250,0,0)'; //red box
ctx.fillRect(100,100,300,300); //box of size 200x200 drawn at (100,100)
ctx.fillStyle='rgb(0,250,0)';

yOff=0;
for (var i=0;i<4;i++){
text="Hello World";
size=20+i*10
font='bold '+size+'px serif';
ctx.font=font;
ctx.textBaseline='top';
width=ctx.measureText(font,text).width;
height=size;

x=100+(300-width)/2; //draw inside the rectangle of 100x100 at pos (0,0)
y=(300-height)/2+yOff; //draw inside the rectangle of 100x100 at pos (0,0)
ctx.fillText(text,x,y);
yOff+=50
}
}
</script>
</head>
<body onload="writeText();" bgcolor="yellow">
<canvas name="canvas" id="canvas" width="500" height="500"></canvas>
</body>
</html>

最佳答案

您不小心每次测量的是 font 字符串而不是 text!

measureText 只有一个参数,而您给了它两个。应该只是

width = ctx.measureText(text).width;

在 jsfiddle 中:

http://jsfiddle.net/PtSAf/19/

关于html Canvas 文本大小不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com