Home > Web Front-end > JS Tutorial > body text

How to draw a tree with js code

零到壹度
Release: 2018-04-14 15:44:17
Original
3513 people have browsed it

The content of this article is to share with you how to draw a tree using js code. It has a certain reference value. Friends in need can refer to it

Create a new HTML document in one step:

<html>  
 <head>   
 <style  type="text/css">   
 /*设置body样式*/      
 body{   
   overflow:hidden;     
   background: black; 
 }   
 </style>   
 </head>   
 <!--设置屏幕背景黑色-->   
 <body>     
    <script src="js.js"></script>   
 </body>
</html>
Copy after login

The second step is to create a js document:

//创建画布
var mycanvas=document.createElement("canvas");
//设置树的宽度和高度
mycanvas.width=1500;
mycanvas.height=900;
//绘制画布的对象并设置为2D
var context=mycanvas.getContext("2d");
//设置划线的类型颜色
context.strokeStyle="#ff00ff";
//设置线的宽度
context.lineWidth=2;
//将画布添加到窗体上
document.body.appendChild(mycanvas);
///////////////////////////////////////////
/*---------------画图部分----------------*/
///////////////////////////////////////////
//画树深度
var n=10;
//设置初始角度
var th=-Math.PI/2;
//设置初始位置
var x0=700;
var y0=700;
//调用绘图函数
draw(n-1,700,700,100,th);
/*------------绘制树的函数-------------------*/
function draw(n,x0,y0,length,th){//(画树深度,起始位置x0,y0,长度,度数)
      if(n==0)
  return;
      //计算线条末端坐标
  var x1=x0+length*Math.cos(th);
  var y1=y0+length*Math.sin(th);
  //画线
      drawline(x0,y0,x1,y1);
  //画子树递归
  draw(n-1,x1,y1,0.8*length*(Math.random()+0.4),th+(20+Math.random()*5)*Math.PI/180);
  draw(n-1,x1,y1,0.6*length*(Math.random()+0.5),th-(30+Math.random()*5)*Math.PI/180);
}
/*--------------绘制线段-----------------------*/
function drawline(x0,y0,x1,y1){
context.moveTo(x0,y0);//设置绘制的起点
context.lineTo(x1,y1);//设置线段的末尾
context.stroke();     //绘制
}
Copy after login

The final result is as shown below :




related suggestion:

python drawing trees and forests

Drawing a tree

How to use js Code to draw a tree

The above is the detailed content of How to draw a tree with js code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!