我有一条使用 p5.js 绘制的指数曲线,它随着时间的推移而绘制如下:
但是,我试图让它以这样一种方式响应,即随着曲线的增长,它总是在 Canvas 内完全可见。
以下是我要实现的截图:
在网站上找到的工作示例
正如您在此示例中看到的那样,一旦它到达 Canvas 的边缘,它就会“缩小”以使 Canvas 适合整个曲线,因此由于它永远不会离开 Canvas ,因此曲线弯曲得越多成长。
为了尝试实现这一点,我探索了使用比例 scale(x / 100, y / 100)
一旦达到 Canvas 的限制就会被触发。这样, Canvas 开始按比例缩放曲线的扩展。
但是,使用这种方法并不能解决我的问题,因为在向曲线添加点的同时减少缩放似乎不会使曲线不再增长。
这是我当前(更新)的代码:
var y = 49;
var x = 0;
var inc = 0.02;
var translateY;
let createTopY = false;
let createTopX = false;
var topY;
var percentageIncY = 100;
var perecntageIncX = 100;
// Scaling
var scaleX = 1
var scaleY = 1
function setup() {
createCanvas(400, 200);
background(20, 25, 29)
}
function draw() {
frameRate(20)
// Set curve history for continuous lines
let prev_x = x
let prev_y = y
// Recreate canvas position (origin) based on Scale Y (zoom)
translateY = height * scaleY
translate(0, (height - translateY) + 49 ) // 49 is the initial y value
scale(scaleX, scaleY)
// Exponential curve values
x = x + 5 // Approximate
y = y + y * inc
// Draw curve
strokeWeight(3)
stroke(229, 34, 71);
line(prev_x, height - prev_y, x, height - y);
// Create topY when top at scale(1) is reached
if (createTopY !== true) checkInt(y)
if (createTopX !== true) checkInt(x)
//-------------- SCALING ---------------//
// From TopX, decrease scale exponentialy
if (x > width - 20) { // Temporarily set to 20 (50-30) to better visualize
// The increased value of x in % starting at topX
percentageIncX = (x * 100) / (width - 20)
// Decrease scaleX exponentialy
scaleX = 100 / percentageIncX
print(
"% increase X: " +
percentageIncX
)
}
// From topY, decrease scale exponentialy
if (y > height + 20) { // Temporarily set to 20 (50-30) to visualize
// The increased value of y in % starting at topY
percentageIncY = (y * 100) / (height + 20) // Temporarily set to 20 (50-30) to better visualize
// Decrease scaleY exponentialy
scaleY = 100 / percentageIncY
print(
"% increase Y: " +
percentageIncY
)
}
//-------------------------------------//
}
const checkInt = (prop) => {
const parsed = int(prop)
if (parsed > height + 20) { // Temporarily set to 20 (50-30) to better visualize
createTopY = true
createTopX = true
topY = y
print('createTopY is: ' + createTopY)
print('createTopX is: ' + createTopX)
print("---START SCALING---")
print('starting at ' + y)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
最佳答案
使用 frameRate()
控制每秒显示的帧数。用线段 ( line()
) 缝合曲线,而不是用单个点 ( ellipse()
) 绘制,以绘制一条没有中断的曲线。
var y = 1;
var x = 0;
var inc = 0.01;
function setup() {
createCanvas(400, 400);
background(100)
frameRate(100)
}
function draw() {
let prev_x = x;
let prev_y = y;
x = x + 0.5
y = y + y * inc;
noFill();
stroke(255, 0, 0, 255);
strokeWeight(3);
line(prev_x, height-prev_y, x, height-y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>
关于javascript - 如何使我绘制的指数函数在 Canvas 内增长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65710528/