code show as below:
<!--Author:Mr.Pan_学狂-->
<!--finish_time:2020/11/12-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>分叉随机二叉树</title>
</head>
<body>
<svg id="mySVG" width=800 height=600></svg>
<script>
var w = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;//获取屏幕宽度
var h = window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;//获取屏幕高度
var mysvg = document.getElementById("mySVG");
mysvg.setAttribute("width",w*0.9);//修改SVG的宽度
mysvg.setAttribute("height",h*0.9);//修改SVG的高度
var length = 200;//起始长度
rate = 0.6;//衰减系数
var x0=w/2;//第一截线段的起点(x0,y0)
var y0 = h;
var count = 7;
var iter = 0;
//定义递归二叉树函数
function show(x0,y0,length,rate,a,count){
iter++
var x1 = x0;
var y1 = y0;
var x2 = x1+length*(0.5+0.5*Math.random())*Math.cos(a);//线段的长度添加随机
var y2 = y1+length*(0.5+0.5*Math.random())*Math.sin(a);//线段的长度添加随机
svgline = document.createElement("line");
mysvg.appendChild(svgline);
var aL = a - Math.PI/4*(0.5+0.5*Math.random());//随机左旋角度,做小的改动,数值不用太大。
var aR = a + Math.PI/4*(0.5+0.5*Math.random());//随机右旋角度,做小的改动,数值不用太大。
svgline.outerHTML="<line x1="+x1+" y1="+y1+" x2="+x2+" y2="+y2+" style='stroke:rgb(0,"+(iter)+",0);stroke-width:"+(count)+"' />";
if(count>0){
show(x2,y2,length*rate,rate,aL,count-1);//调用函数
show(x2,y2,length*rate,rate,aR,count-1);
}
}
show(x0,y0,length,rate,-Math.PI/2,count);//调用函数
</script>
</body>
</html>
The results of the operation are as follows:
Finally, thank you all for coming to watch my article. There may be many improprieties in the article, and I hope to point out Hehaihan.