码迷,mamicode.com
首页 > 其他好文 > 详细

canvas成长树

时间:2018-02-28 14:41:08      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:set   scale   save   restore   i++   meta   oct   tco   随机   

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas成长树</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById(‘canvas‘)
const ctx = canvas.getContext(‘2d‘)

const W = canvas.width = 900
const H = canvas.height = 700

canvas.style.border = ‘8px solid #bcbcbc‘

// rp([1, 3]) ==> 1 | 2 | 3
// rp([3, 1], true) ==> 1 - 3 之间随机的小数
const rp = function (arr, uint){
const min = Math.min(...arr)
const max = Math.max(...arr)
const ret = Math.random() * (max - min) + min
return uint ? ret : Math.round(ret)
}

const maxBranch = 3

tree(ctx, W/2, H/2 + 200, 70, -Math.PI/2, 14, 20)

function tree(ctx, startX, startY, branchLen, angle, depth, branchWidth) {
const endX = startX + branchLen * Math.cos(angle)
const endY = startY + branchLen * Math.sin(angle)

const color = (depth--) < maxBranch - 1 ? `rgb(0, ${rp([128, 196])}, 0)` : ‘rgb(68, 50, 25)‘

ctx.save()
ctx.lineCap = ‘round‘
ctx.lineWidth = branchWidth
ctx.strokeStyle = color
ctx.beginPath()
ctx.moveTo(startX, startY)
ctx.lineTo(endX, endY)
ctx.stroke()
ctx.restore()

if (!depth) return

const subBranches = rp([1, maxBranch])

for (let i=0; i<subBranches; i++) {
setTimeout(
tree,
0,
ctx,
endX,
endY,
branchLen * rp([0.7, 1], true),
angle + rp([-Math.PI/5, Math.PI/5], true),
depth,
branchWidth * 0.72
)
}
}

</script>
</body>
</html>
原文来自于:https://www.cnblogs.com/jtxiao/archive/2018/02/28/8482837.html

canvas成长树

标签:set   scale   save   restore   i++   meta   oct   tco   随机   

原文地址:https://www.cnblogs.com/JeneryYang/p/8483407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!