限制一行的长度
Limit the length of a line
我正在尝试绘制一条代表 'slingshot' 的线,我希望它具有最大绘制长度。
在第 5 页中,我在位置 A 和位置 B 之间画了一条线:
line(posA.x, posA.y, posB.x, posB.y);
posA是鼠标x和y。 posB 是圆在 canvas.
上的位置
我想做的是限制线条的长度,使其永远不会超过 40px,但仍然从圆圈指向鼠标。
2点之间的Euclidean distance由sqrt(dx*dx + dy*dy)
计算。
如果将一个点的向量除以另一个点的向量,则会得到长度为 1 的 Unit vector。
计算从posA
到posB
的单位向量乘以40:
// (dx, dy): vector form "posA" to "posB"
let dx = posB.x-posA.x;
let dy = posB.y-posA.y;
// dist : euclidean distance, length of the vecotr
let dist = Math.sqrt(dx*dx + dy*dy);
// (ux, uy): unit vector form 'posA' in direction to 'posB', with length 1
let ux = dx / dist;
let uy = dy / dist;
// (x2, y2): point with a distance of 40 from "posA" an the vector to "posB"
let x2 = posA.x + ux * 40;
let y2 = posA.y + uy * 40;
line(posA.x, posA.y, x2, y2);
在 p5.js 中,您可以使用 p5.Vector
进行所有这些计算。
.sub()
两点相减,计算向量
.normalize()
计算长度为 1 的单位向量
.mult()
缩放向量
.add()
将向量添加到点
let A = createVector(posA.x, posA.y);
let B = createVector(posB.x, posB.y);
let P = B.sub(A).normalize().mult(40).add(A);
line(posA.x, posA.y, P.x, P.y);
看例子:
function setup() {
createCanvas(200, 200);
}
function draw() {
background(0, 0, 0);
stroke(255, 0, 0);
strokeWeight(5);
let A = createVector(width/2, height/2);
let B = createVector(mouseX, mouseY);
let P = B.sub(A).normalize().mult(40).add(A);
line(A.x, A.y, P.x, P.y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
我正在尝试绘制一条代表 'slingshot' 的线,我希望它具有最大绘制长度。
在第 5 页中,我在位置 A 和位置 B 之间画了一条线:
line(posA.x, posA.y, posB.x, posB.y);
posA是鼠标x和y。 posB 是圆在 canvas.
上的位置我想做的是限制线条的长度,使其永远不会超过 40px,但仍然从圆圈指向鼠标。
2点之间的Euclidean distance由sqrt(dx*dx + dy*dy)
计算。
如果将一个点的向量除以另一个点的向量,则会得到长度为 1 的 Unit vector。
计算从posA
到posB
的单位向量乘以40:
// (dx, dy): vector form "posA" to "posB"
let dx = posB.x-posA.x;
let dy = posB.y-posA.y;
// dist : euclidean distance, length of the vecotr
let dist = Math.sqrt(dx*dx + dy*dy);
// (ux, uy): unit vector form 'posA' in direction to 'posB', with length 1
let ux = dx / dist;
let uy = dy / dist;
// (x2, y2): point with a distance of 40 from "posA" an the vector to "posB"
let x2 = posA.x + ux * 40;
let y2 = posA.y + uy * 40;
line(posA.x, posA.y, x2, y2);
在 p5.js 中,您可以使用 p5.Vector
进行所有这些计算。
.sub()
两点相减,计算向量.normalize()
计算长度为 1 的单位向量
.mult()
缩放向量.add()
将向量添加到点
let A = createVector(posA.x, posA.y);
let B = createVector(posB.x, posB.y);
let P = B.sub(A).normalize().mult(40).add(A);
line(posA.x, posA.y, P.x, P.y);
看例子:
function setup() {
createCanvas(200, 200);
}
function draw() {
background(0, 0, 0);
stroke(255, 0, 0);
strokeWeight(5);
let A = createVector(width/2, height/2);
let B = createVector(mouseX, mouseY);
let P = B.sub(A).normalize().mult(40).add(A);
line(A.x, A.y, P.x, P.y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>