使用canvas画树很简单。以下是大约80行代码的解决方案。
有几个人试图重新创建视频中的交互环境。其中之一是由GitHub用户tnlogy创建的这些尝试中的一个。他的环境允许您在代码中选择数字并使用滑块实时更改运行演示。我分支了他的代码以包含树演示。
交互式树演示:
https://brianpeiris.github.io/live-coding/client/
简单树演示:
http://jsfiddle.net/brianpeiris/v9zD6/show
简单树演示源代码:
var
drawLeaf = function (cx, xx, yy) {
var
leafAlpha = 8/10,
leafSize = 7;
cx.beginPath();
cx.fillStyle = (
"rgba(" +
Math.round(220 + (Math.random() * 50)) + ", " +
Math.round(180 + (Math.random() * 50)) + ", " +
Math.round(220 + (Math.random() * 50)) + ", " +
leafAlpha +
")"
);
cx.arc(xx, yy, leafSize, 0, Math.PI * 2);
cx.fill();
},
drawBranch = function (ii, cx, xx, yy, level, levels, angle, numBranches) {
var
branchLength = 44,
subBranchWidthFactor = 2,
sweep = Math.PI * 25/30,
branchTweakMagnitude = 52/50,
tt;
cx.beginPath();
cx.lineWidth = (levels - level) * subBranchWidthFactor;
tt = (
sweep * ii / (numBranches - 1) + angle -
sweep / 2 + Math.PI +
Math.random() * 0.5 * branchTweakMagnitude
);
cx.moveTo(xx, yy);
newXX = xx + Math.sin(tt) * branchLength;
newYY = yy + Math.cos(tt) * branchLength;
cx.lineTo(newXX, newYY);
cx.stroke();
drawBranchesAndLeaves(cx, newXX, newYY, level + 1, levels, Math.PI + tt);
},
drawBranchesAndLeaves = function (cx, xx, yy, level, levels, angle) {
var
numBranches = 5,
ii, newXY;
if (level === levels) {
drawLeaf(cx, xx, yy);
return;
}
else {
for (ii = 0; ii < numBranches; ii++) {
drawBranch(ii, cx, xx, yy, level, levels, angle, numBranches);
}
}
},
drawTree = function(cx, ww, hh) {
var trunkX = ww / 2, trunkY = hh - 165;
cx.strokeStyle = "black";
cx.lineWidth = 13;
cx.lineCap = "round";
cx.moveTo(trunkX, hh);
cx.lineTo(trunkX, trunkY);
cx.stroke();
drawBranchesAndLeaves(cx, trunkX, trunkY, 0, 3, 0);
},
width = 350,
height = 350,
canvas = $('<canvas width="' + width + '" height="' + height + '"></canvas>'),
ctx = canvas[0].getContext("2d");
$('body').append(canvas);
drawTree(ctx, width, height);