【问题标题】:How do I write something directly inside the circle?如何直接在圈内写东西?
【发布时间】:2018-11-08 13:49:25
【问题描述】:

我想直接在圈内写点东西,但不知道怎么写。我知道我可以写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;

【问题讨论】:

    标签: javascript html reactjs debugging


    【解决方案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

    【讨论】:

      【解决方案2】:

      好吧,如果你算一下:

      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

      希望能有所帮助!

      【讨论】:

      • 啊,好吧,但是您是如何通过数学计算从 100、75 中得出 95、80 的?另外,我试过这个并尝试改变坐标,但我根本看不到test
      猜你喜欢
      • 1970-01-01
      • 2010-10-08
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      相关资源
      最近更新 更多