gpt4 book ai didi

javascript - 在 Javascript Canvas 中动画分形树

转载 作者:行者123 更新时间:2023-11-29 23:24:04 25 4
gpt4 key购买 nike

在 youtube 上看到 Coding Train 中关于分形树的视频后,我尝试自己构建一个。效果很好,我尝试了一些变量以获得不同的结果。

我很想看到树像被风吹过一样移动。我尝试了不同的方法,例如稍微旋转 Twig 或一些较小的物理实现,但都失败了。

所以我的问题是:什么是渲染分形树并赋予它某种“生命力”的最佳方法,就像风中的轻微摇晃一样。有什么好的引用吗?我需要物理吗? -> 如果是这样,我必须去哪里看?如果不是 -> 我怎么能伪造这样的效果?

我很高兴能得到每一个帮助。

创意来源:https://www.youtube.com/watch?v=0jjeOYMjmDU

最佳答案

风中的树。

以下是在风中弯曲 Twig 的一些短点。由于整个解决方案很复杂,您将不得不从代码中获取您能获取的信息。

该代码包含一个种子随机数函数。随机递归树渲染器,质量差的随机风力发电机,全部使用动画循环绘制在 Canvas 上。

要施加风,您需要向每个 Twig 添加一个弯曲力,该弯曲力与 Twig 与风的 Angular 成正比。

因此,如果您在 dir 方向有一个分支和直风wDir弯曲力需要的缩放量是

var x = Math.cos(dir);    // get normalize vector for the branch
var y = Math.sin(dir);

var wx = Math.cos(wDir); // get normalize vector for the wind
var wy = Math.sin(wDir);

var forceScale = x * wy - y * wx;

分支的长度也会影响力的大小,您将分支的矢量延长成与其长度成正比

var x = Math.cos(dir) * length;    // get normalize vector for the branch
var y = Math.sin(dir) * length;

var wx = Math.cos(wDir); // get normalize vector for the wind
var wy = Math.sin(wDir);

var forceScale = x * wy - y * wx;

使用这种方法可以确保 Twig 不会被风吹弯。

还有 Twig 的粗细,这是一个与横截面积相关的多项式关系。这是未知的,因此按比例缩放到树的最大厚度(假设树基不能弯曲的近似值,但末端 Twig 可以弯曲很多。)

然后弯曲 Twig 的弹力将有一个力将 Twig 移回其正常位置。这就像 Spring 一样,与风力非常相似。由于计算和内存负载将开始压倒 CPU,我们可以作弊并利用风也以一点弹性回弹。

还有那棵树。

树需要是随机的,但由于是分形的,您不想存储每个分支。所以你还需要一个种子随机生成器,它可以在每个渲染过程开始时重置。树在每次迭代中随机呈现,但因为每次获得相同的树时随机数都从相同的种子开始。

例子

在阵风中随机绘制树和风。风是随机的,因此树可能不会立即移动。

单击 TreeMap 像以重新播种树的随机种子值。

我没有看视频,但这些东西很标准,所以递归函数应该与你可能拥有的相去不远。我确实看到了 youTube 的封面图片,看起来这棵树没有随机性。要删除随机性,请设置 leng , ang , width最小值,最大值相同。例如angMin = angMax = 0.4;将删除随机分支 Angular 。

风力将达到旋风强度(美国为飓风)以查看最大效果。

有无数的神奇数字,最重要的是带有注释的常量。

const ctx = canvas.getContext("2d");

// click function to reseed random tree
canvas.addEventListener("click",()=> {
treeSeed = Math.random() * 10000 | 0;
treeGrow = 0.1; // regrow tree
});


/* Seeded random functions
randSeed(int) int is a seed value
randSI() random integer 0 or 1
randSI(max) random integer from 0 <= random < max
randSI(min, max) random integer from min <= random < max
randS() like Math.random
randS(max) random float 0 <= random < max
randS(min, max) random float min <= random < max

*/
const seededRandom = (() => {
var seed = 1;
return { max : 2576436549074795, reseed (s) { seed = s }, random () { return seed = ((8765432352450986 * seed) + 8507698654323524) % this.max }}
})();
const randSeed = (seed) => seededRandom.reseed(seed|0);
const randSI = (min = 2, max = min + (min = 0)) => (seededRandom.random() % (max - min)) + min;
const randS = (min = 1, max = min + (min = 0)) => (seededRandom.random() / seededRandom.max) * (max - min) + min;


/* TREE CONSTANTS all angles in radians and lengths/widths are in pixels */
const angMin = 0.01; // branching angle min and max
const angMax= 0.6;
const lengMin = 0.8; // length reduction per branch min and max
const lengMax = 0.9;
const widthMin = 0.6; // width reduction per branch min max
const widthMax = 0.8;
const trunkMin = 6; // trunk base width ,min and max
const trunkMax = 10;
const maxBranches = 200; // max number of branches


const windX = -1; // wind direction vector
const windY = 0;
const bendability = 8; // greater than 1. The bigger this number the more the thin branches will bend first

// the canvas height you are scaling up or down to a different sized canvas
const windStrength = 0.01 * bendability * ((200 ** 2) / (canvas.height ** 2)); // wind strength


// The wind is used to simulate branch spring back the following
// two number control that. Note that the sum on the two following should
// be below 1 or the function will oscillate out of control
const windBendRectSpeed = 0.01; // how fast the tree reacts to the wing
const windBranchSpring = 0.98; // the amount and speed of the branch spring back

const gustProbability = 1/100; // how often there is a gust of wind

// Values trying to have a gusty wind effect
var windCycle = 0;
var windCycleGust = 0;
var windCycleGustTime = 0;
var currentWind = 0;
var windFollow = 0;
var windActual = 0;


// The seed value for the tree
var treeSeed = Math.random() * 10000 | 0;

// Vars to build tree with
var branchCount = 0;
var maxTrunk = 0;
var treeGrow = 0.01; // this value should not be zero

// Starts a new tree
function drawTree(seed) {
branchCount = 0;
treeGrow += 0.02;
randSeed(seed);
maxTrunk = randSI(trunkMin, trunkMax);
drawBranch(canvas.width / 2, canvas.height, -Math.PI / 2, canvas.height / 5, maxTrunk);
}

// Recusive tree
function drawBranch(x, y, dir, leng, width) {
branchCount ++;
const treeGrowVal = (treeGrow > 1 ? 1 : treeGrow < 0.1 ? 0.1 : treeGrow) ** 2 ;

// get wind bending force and turn branch direction
const xx = Math.cos(dir) * leng * treeGrowVal;
const yy = Math.sin(dir) * leng * treeGrowVal;
const windSideWayForce = windX * yy - windY * xx;

// change direction by addition based on the wind and scale to
// (windStrength * windActual) the wind force
// ((1 - width / maxTrunk) ** bendability) the amount of bending due to branch thickness
// windSideWayForce the force depending on the branch angle to the wind
dir += (windStrength * windActual) * ((1 - width / maxTrunk) ** bendability) * windSideWayForce;

// draw the branch
ctx.lineWidth = width;
ctx.beginPath();
ctx.lineTo(x, y);
x += Math.cos(dir) * leng * treeGrowVal;
y += Math.sin(dir) * leng * treeGrowVal;
ctx.lineTo(x, y);
ctx.stroke();



// if not to thing, not to short and not to many
if (branchCount < maxBranches && leng > 5 && width > 1) {
// to stop recusive bias (due to branch count limit)
// random select direction of first recusive bend
const rDir = randSI() ? -1 : 1;

treeGrow -= 0.2;
drawBranch(
x,y,
dir + randS(angMin, angMax) * rDir,
leng * randS(lengMin, lengMax),
width * randS(widthMin, widthMax)
);
// bend next branch the other way
drawBranch(
x,y,
dir + randS(angMin, angMax) * -rDir,
leng * randS(lengMin, lengMax),
width * randS(widthMin, widthMax)
);
treeGrow += 0.2;
}
}

// Dont ask this is a quick try at wind gusts
// Wind needs a spacial component this sim does not include that.

function updateWind() {
if (Math.random() < gustProbability) {
windCycleGustTime = (Math.random() * 10 + 1) | 0;
}
if (windCycleGustTime > 0) {
windCycleGustTime --;
windCycleGust += windCycleGustTime/20
} else {
windCycleGust *= 0.99;
}
windCycle += windCycleGust;
currentWind = (Math.sin(windCycle/40) * 0.6 + 0.4) ** 2;
currentWind = currentWind < 0 ? 0 : currentWind;
windFollow += (currentWind - windActual) * windBendRectSpeed;
windFollow *= windBranchSpring ;
windActual += windFollow;
}
requestAnimationFrame(update);
function update() {
ctx.clearRect(0,0,canvas.width,canvas.height);
updateWind();
drawTree(treeSeed);
requestAnimationFrame(update);
}
body {
font-family : arial;
}
<canvas id="canvas" width="250" heigth="200"></canvas>
Click tree to reseed.

更新

我刚刚注意到风和 Twig 的长度是绝对的,因此在较大的 Canvas 上绘制树会产生太大的弯曲力, Twig 会弯曲超过风矢量。

要扩大 sim 的规模,要么通过全局规模变换,要么减少 windStrength恒定为某个较小的值。您将不得不使用该值作为其二阶多项式关系。我的猜测是将它乘以 (200 ** 2) / (canvas.height ** 2)其中 200 是示例 Canvas 的大小,canvas.height是新的 Canvas 尺寸。

我已将计算添加到示例中,但它并不完美,因此当您缩放时,您将不得不更改值 windStrength如果弯曲太远或不够,(第一个数字)向下或向上。

关于javascript - 在 Javascript Canvas 中动画分形树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49785734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com