将文本绘制到线 (x1, y1, x2, y2) 时的旋转和平移值(使用 p5.js,处理 ... atan2)

rotation & translate value when draw text to line(x1, y1, x2, y2) (use p5.js, processing ... 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, 0)
    point(x, y);
    point(x2, y2);
    textSize(10);
    noStroke();
    text(`x(${x}, ${y})`, x, y);
    text(`x(${x2}, ${y2})`, x2, 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, 0, 255);

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

我想修复文本适合行

这个问题我纠结了五天。 在几乎不了解 theta 和切线等之后, 停留在这一步让我对下一步没有耐心......请帮忙!

此处放置文本的基本思路是,您希望平移到 line/shape 上的一个精确点,然后旋转并放置您的文本,例如,您可以执行以下操作将旋转后的文本放置在行首:

//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, 0);

如果您希望文本位于沿 line/shape 的特定点,您可以执行一些三角函数来找到确切的点,然后使用这些点进行翻译:

//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, 0);