javascript - 如何直接在圆圈内写东西?

标签 javascript html reactjs debugging

我想直接在圆圈内写一些东西,但我不知道该怎么做。我知道我可以只写 ctx.fillText("test", 10, 30); ,它会移到右侧,但我觉得这是一种低效的方法。

我该如何实现这一目标?下面是我所指的图像。

enter image description here

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

enter image description here

关于javascript - 如何直接在圆圈内写东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209081/

相关文章:

javascript - 如何选择最里面的元素?

python - HTML 多空格对齐

javascript - react 中的脚本加载

javascript - 如何在react-router中创建 `/orders/:id/detail`路径

reactjs - React Hooks - 如何使用 useEffect 之外的变量声明来定位元素子元素(使用 useRef)?

javascript - jQuery 应用事件处理程序的最佳方式

javascript - Mozilla 关闭示例

javascript - 给定页面标题列表,在 MediaWiki 页面中自动添加 wiki 链接

javascript - 使用 Snap.Select 时 SVG 未捕获类型错误

jquery - 如何让这些元素显示在同一行上?