gpt4 book ai didi

javascript - 如何根据文本长度动态地居中 Canvas javascript

转载 作者:行者123 更新时间:2023-11-30 17:46:22 25 4
gpt4 key购买 nike

我想居中“我的文字!”无论字符串的长度如何...随着文本的长度变长,x 坐标需要变小。

如何获取字符串的 x 长度?

<html>
<head>
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, 0, 0);
context.font = "12pt Arial";
context.fillText("My TEXT!", 20, 20);
};
imageObj.src = "http://images.google.com/intl/en_ALL/images/srpr/logo11w.png";
};
</script>
</head>
<body>
<canvas width="282px" height="177px" id="myCanvas"></canvas>
</body>
</html>

最佳答案

只需将其添加到您的代码中:

imageObj.onload = function(){
context.drawImage(imageObj, 0, 0);

context.font = "12pt Arial";

/// set text alignment to center
context.textAlign = 'center';

/// draw from center
context.fillText("My TEXT!", canvas.width * 0.5, 20);
};

如果您需要自己获取 x 坐标,则需要根据文本的宽度(设置字体后)计算它:

var width = context.measureText(myText).width;
var x = (canvas.width - width) * 0.5;

关于javascript - 如何根据文本长度动态地居中 Canvas javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080991/

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