将文字绘制到linex1,y1,x2,y2时旋转和转换值使用p5.js,正在处理... atan2

问题描述

当我将文本绘制到线条上并随着theta旋转时 文本离行很远。 我认为,原因在于翻译,但我不知道如何解决。 这是我的代码(p5.js)

function setup() {
    createCanvas(500,700);
    
    x = 100;
    y = 200;
    x2 = 300;
    y2 = 500;
}

function draw() {
    background(200);

    strokeWeight(2);
    stroke(0,255,0);
    line(x,y,x2,y2);

    strokeWeight(5);
    stroke(255,0)
    point(x,y);
    point(x2,y2);
    textSize(10);
    nostroke();
    text(`x(${x},${y})`,x,y);
    text(`x(${x2},${y2})`,y2);

    // Whether this code needs "translate" or not,// I want to kNow same method when I draw text to line,circle ... so on
    translate(x,y);
    rotate(atan2(y2 - y,x2 - x));

    nostroke();
    textSize(50);
    fill(0,255);

    text("A",y);
    rect(x,50,50);
}

enter image description here

我想将文本调整为紧密对齐

enter image description here

我已经为这个问题苦苦挣扎了五天。 在几乎不了解θ和切线等之后, 保持这一步会让我急于下一步...请帮助!

解决方法

此处放置文本的基本思想是,您希望平移到直线/形状上的确切点,然后旋转并放置文本,例如,您可以执行以下操作将旋转的文本放置在线条的开头行:

//Translate to the start of the line
translate(x,y);
//rotate to the desired angle (for example 20)
rotate(20);
//place the text at the start of the line
text("A",0);

如果您希望文本位于直线/形状上的特定点,则可以执行三角函数以找到确切的点,然后将这些点用于翻译:

//Translate to a point on the line before you rotate
translate(linePointX,linePointY);
//rotate to the desired angle (for example 20)
rotate(20);
//place the text at 0,0 (the point of the last translate)
//or increase/decrease the x and y vaues to offset the text
text("A",0);