Как мне написать что-то прямо внутри круга? - PullRequest
0 голосов
/ 08 ноября 2018

Я хотел бы написать что-то прямо внутри круга, но я не уверен, как это сделать. Я знаю, что мог бы просто написать 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;

Ответы [ 2 ]

0 голосов
/ 08 ноября 2018

Вы можете использовать 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

0 голосов
/ 08 ноября 2018

Ну, если вы делаете математику:

the x of the circle is: 100
the y of the circle is: 75
So, the text should be around (95, 80)

Примечание: координата (x, y) text зависит от координаты круга. Как уже было сказано, вы можете сделать его более динамичным:

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.

Надеюсь, что это может помочь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...