如何在圆弧末尾填写文本?

时间:2019-05-27 12:45:11

标签: html canvas

我正在尝试在半圆图内放置文本。我为您简化了弧context.arc(92.5, 92.5, 72.5, 3.141592653589793, 3.7699111843077517, false);,我想在弧的末尾放置一个值2,因为弧代表总值的20%。

到目前为止,我尝试过的是

context.translate(centerX, centerY);
context.save();
context.translate(x, y);
context.fillText('2', 0, 3);
context.restore();

我尝试使用(−ℎ)2+(−)2=2找到x和y的拦截点。但是我不能将文本放在弧的末尾。有人可以帮我解决这个问题吗?谢谢。

1 个答案:

答案 0 :(得分:1)

您将需要找到圆弧的终点:

let x = center.x + radius * Math.cos(endArc);
let y = center.y + radius * Math.sin(endArc);

在这种情况下,圆心在点{x:92.5,y:92.5}中,半径为72.5。结束弧为3.7699111843077517。

我希望这就是你的要求。

const ctx = canvas.getContext("2d");
let cw = canvas.width = 200;
let ch= canvas.height = 200;
ctx.beginPath();
ctx.arc(92.5, 92.5, 72.5, 3.141592653589793, 3.7699111843077517, false);
ctx.stroke();
//find the point where the arc ends
let x = 92.5 + 72.5 * Math.cos(3.7699111843077517);
let y = 92.5 + 72.5 * Math.sin(3.7699111843077517);
// draw the text
ctx.font="12px Arial";  
ctx.textAlign="center";
ctx.textBaseline="bottom"; 
ctx.fillText("2",x,y);
canvas{border:1px solid}
<canvas id="canvas"></canvas>