我想直接在圆圈内写一些东西,但我不知道该怎么做。我知道我可以只写 ctx.fillText("test", 10, 30); ,它会移到右侧,但我觉得这是一种低效的方法。
我该如何实现这一目标?下面是我所指的图像。
import React, {Component} from 'react';
class Login extends Component {
componentDidMount() {
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.fillText("hey", 10, 30);
ctx.stroke();
}
render() {
return (
<div>
<canvas id="myCanvas" width="240" height="200"/>
</div>
);
}
}
export default Login;
最佳答案
您可以使用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
关于javascript - 如何直接在圆圈内写东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209081/