HTML5 canvas画的摇摆的树

来源:互联网 发布:淘宝商城首页 编辑:程序博客网 时间:2024/04/30 04:01
<!doctype html>   
<html>   
<head>   
<meta charset='UTF-8' />   
<title>Tree</title>   
</head>   
<body>   
<canvas id="pad" width='1000' height='500'><a href='http://www.cssass.com'>cssass.com</a>提醒您:ie9以下用户请一边惭愧去吧</canvas>   
</body>   
<script>   
var con=document.getElementById("pad").getContext('2d');   
    con.strokeStyle = '#0f0';   
    con.lineWidth=1.8;   
var Tree=function(x, y, l, angle, n){ 
    var a=[],rand=0,dir=1,val;
    this.init=function(x, y, l, angle, n) {   
        var that=this;   
        if (n>0) {   
            var a_l, a_r, x1, y1, x2, y2;   
            x1 = x+0.5*l*Math.cos(angle*Math.PI/180);   
            y1 = y-0.5*l*Math.sin(angle*Math.PI/180);   
            x2 = x+l*Math.cos(angle*Math.PI/180);   
            y2 = y-l*Math.sin(angle*Math.PI/180);   
            a.push([x, y, x2, y2]);   
            a_l = angle+30;   
            a_r = angle-30;   
            l=l*2/3;   
            that.init(x2, y2, l, angle+rand, n-1);   
            that.init(x1, y1, l*2/3, a_l+rand/2, n-1);   
            that.init(x1, y1, l*2/3, a_r+rand/2, n-1);   
            that.init(x2, y2, l*2/3, a_l+rand/2, n-1);   
            that.init(x2, y2, l*2/3, a_r+rand/2, n-1);   
         };   
    }; 
    this.run=function(){ 
  con.clearRect(0,0,1000,500);
        for(var i=0; i<a.length; i++){   
            this.dw(a[i][0],a[i][1],a[i][2],a[i][3]);   
        };  
  a=[];
    }; 
 this.move=function(){
  var that = this;
  var _s=function(){
   that.change();
   that.init(x, y, l, angle, n);
   that.run();
   setTimeout(_s,100);
  };
  _s();
 };
 this.change=function(){
  val=Math.random()*2;
  rand+=dir*val;
  if(rand>10 || rand<-2){dir=-dir;}  
 };
 this.init(x, y, l, angle, n);
 this.run();
};   
Tree.prototype.dw=function(ax, ay, bx, by){   
    con.beginPath()   
    con.moveTo(ax, ay);   
    con.lineTo(bx, by);   
    con.stroke();   
};   
 
var ss=new Tree(300, 500, 200, 90, 6).move();
</script>
</html>
原创粉丝点击