使用Canvas来模拟画一棵树

首先说一下思路:

从树干开始依次循环指定层数值(不要太大),每次随机画指定限制次数内的树枝(这里是3),然后给数值一定规律循环的颜色。这样就得到了一棵树,也可能像一朵西蓝花。

实现代码:


var Tree = (function(){
var canvas = document.createElement("canvas"),ctx = canvas.getContext("2d"),W = window.innerWidth,H = window.innerHeight;
var maxAngle = Math.PI/2,maxBranch = 3;
canvas.height = H;canvas.width = W;
document.body.appendChild(canvas);
var init = function(x,y){
var x = x || W /2,y = y || H /2 + 100;
draw(x,y,60,-Math.PI/2,12,12);
}
var draw = function(startX,startY,length,angle,depth,branchWidth){
var color,endX,endY,subBranches,newAngle,newLength;
ctx.beginPath();
ctx.moveTo(startX,startY);
endX = startX + length * Math.cos(angle);
endY = startY + length * Math.sin(angle);
ctx.lineCap = 'round';
ctx.lineWidth = branchWidth;
ctx.lineTo(endX,endY);
if(depth--<=2){
color = 'rgb(0,' + (rand(128,192)>>0) + ',0)';
}else{
color = 'rgb(' + (rand(64,128)>>0) + ',50,25)';
}
ctx.strokeStyle = color;
ctx.stroke();
if(!depth) return;
subBranches = rand(1,maxBranch);
branchWidth *= 0.7;
for(var i=0;i<subBranches;i++){
newAngle = angle + rand(-Math.PI/4,Math.PI/4);
newLength = length * rand(0.7,1);
draw(endX,endY,newLength,newAngle,depth,branchWidth)
}

}
var rand = function(min,max){
return Math.random() * (max-min) + min;
}
return {init : init}
})();

在线demo:http://demo.deanhan.cn/js-tree/

  • 支付宝二维码 支付宝
  • 微信二维码 微信

本文地址: https://www.deanhan.cn/js-tree.html

版权声明: 本文为原创文章,版权归 逐梦个人博客 所有,欢迎分享本文,转载请保留出处!

相关文章