HTML and JavaScript draw standard binary tree

Today is another beautiful day, and I have gained something new again. To be honest, it is not ideal to use HTML and JavaScript for visualization, and it is not even as real as pyecharts, but it is also a good choice as a kind of understanding.

Draw the standard binary tree
code as follows:

<!--Author:Mr.Pan_学狂-->
<!--finish time:2020/11/12-->
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>标准二叉树</title>
	</head>
	<body>
		<svg id="mySVG" width="800px" height="600px"></svg><!--设置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;//迭代7次
			var iter = 0;
			//定义递归二叉树
			function show(x0,y0,length,rate,a,count){
     
     
				iter++;
				var x1=x0;
				var y1=y0;
				var x2=x1+length*Math.cos(a);
				var y2=y1+length*Math.sin(a);//函数表达式
				svgline = document.createElement("line");//创建标签line
				mysvg.appendChild(svgline);
				svgline.outerHTML="<line x1="+x1+" y1="+y1+" x2="+x2+" y2="+y2+" style='stroke:rgb(99,99,99);stroke-width:2' />";
				var aL = a - Math.PI/4;//左旋角度
				var aR = a + Math.PI/4;//右旋角度
				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 result is as follows:
Insert picture description here
Finally, thank you all for coming to watch my article, I am very grateful, there may be many improprieties in the article, and I hope to point out He Haihan.

Guess you like

Origin blog.csdn.net/weixin_43408020/article/details/109641287