【问题标题】:noisy line between two specific points P5.js两个特定点 P5.js 之间的嘈杂线
【发布时间】:2021-09-30 08:52:42
【问题描述】:
我试图在两个特定点之间画一条嘈杂的线(使用 perlin 噪声)。
例如A(100, 200) 和B(400,600)。
这条线可以是一个点系列。
绘制随机噪声线非常清晰,但我不知道如何计算距离特定点。
P5.js. 的工作
我还没有编写任何要上传的代码。
请问谁能帮帮我?
【问题讨论】:
标签:
javascript
processing
p5.js
【解决方案1】:
我尝试添加足够的 cmets,以便您能够了解如何完成这样的事情。如果您还没有意识到一些事情,那么您应该让自己意识到,如果您缺少这些,很难说:
// The level of detail in the line in number of pixels between each point.
const pixelsPerSegment = 10;
const noiseScale = 120;
const noiseFrequency = 0.01;
const noiseSpeed = 0.1;
let start;
let end;
function setup() {
createCanvas(400, 400);
noFill();
start = createVector(10, 10);
end = createVector(380, 380);
}
function draw() {
background(255);
let lineLength = start.dist(end);
// Determine the number of segments, and make sure there is at least one.
let segments = max(1, round(lineLength / pixelsPerSegment));
// Determine the number of points, which is the number of segments + 1
let points = 1 + segments;
// We need to know the angle of the line so that we can determine the x
// and y position for each point along the line, and when we offset based
// on noise we do so perpendicular to the line.
let angle = atan2(end.y - start.y, end.x - start.x);
let xInterval = pixelsPerSegment * cos(angle);
let yInterval = pixelsPerSegment * sin(angle);
beginShape();
// Always start with the start point
vertex(start.x, start.y);
// for each point that is neither the start nor end point
for (let i = 1; i < points - 1; i++) {
// determine the x and y positions along the straight line
let x = start.x + xInterval * i;
let y = start.y + yInterval * i;
// calculate the offset distance using noice
let offset =
// The bigger this number is the greater the range of offsets will be
noiseScale *
(noise(
// The bigger the value of noiseFrequency, the more erretically
// the offset will change from point to point.
i * pixelsPerSegment * noiseFrequency,
// The bigger the value of noiseSpeed, the more quickly the curve
// fluxuations will change over time.
(millis() / 1000) * noiseSpeed
) - 0.5);
// Translate offset into x and y components based on angle - 90°
// (or in this case, PI / 2 radians, which is equivalent)
let xOffset = offset * cos(angle - PI / 2);
let yOffset = offset * sin(angle - PI / 2);
vertex(x + xOffset, y + yOffset);
}
vertex(end.x, end.y);
endShape();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
此代码生成锯齿状线条,但可以使用curveVertex() 对其进行平滑处理。此外,使线准确地通过起点和终点有点棘手,因为下一个点可能会被大量偏移。您可以通过使noiseScale 非常取决于当前点距端点的距离来解决此问题。例如,这可以通过将 noiseScale 乘以 sin(i / points.length * PI) 来完成。