我想在圈子内直接写一些东西,但是我不确定该怎么做。我知道我可以只写php -r "echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';"
,它会移到右边,但是我觉得那是一种低效的方式。
我将如何实现?下面是我所指的图像。
ctx.fillText(" test", 10, 30);
答案 0 :(得分:1)
您可以使用measureText
获取文本的宽度并计算文本起点的坐标:
class App extends React.Component {
componentDidMount() {
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
const x_arc = 100;
const y_arc = 75;
const radius = 50;
const text = "hey";
const text_width = ctx.measureText(text).width;
const x_text = x_arc - text_width / 2;
const y_text = y_arc;
ctx.beginPath();
ctx.arc(x_arc, y_arc, radius, 0, 2 * Math.PI);
ctx.fillText("hey", x_text, y_text);
ctx.stroke();
}
render() {
return (
<div>
<canvas id="myCanvas" width="240" height="200" />
</div>
);
}
}
此处是指向沙盒的链接:https://codesandbox.io/s/j377qol3ww
答案 1 :(得分:0)
好吧,如果你做数学:
the x of the circle is: 100
the y of the circle is: 75
So, the text should be around (95, 80)
注意:text
的(x,y)坐标取决于一个圆。话虽如此,您可以使其更具动态性:
const circleCords = { x: 100, y: 75 }
// You can adjust the x, y of the text. Because `5` is just for testing.
// I mean by that, that you would have to get the width of the text and then calculate how much you'd subtract from the circleCords!
const textCords = { x: circleCords - 5, y: circleCords + 5 }
ctx.arc(circleCords.x, circleCords.y, 50, 0,2*Math.PI);
ctx.fillText("hey", textCords.x, textCords.y);
如果文本的宽度始终恒定,则可以根据需要减去随机数,这样就可以了。在这种情况下,
5
。
希望有帮助!