源代码为JavaScript树,其功能在“Inventing on Principle”视频

前端之家收集整理的这篇文章主要介绍了源代码为JavaScript树,其功能在“Inventing on Principle”视频前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我受到Bret Victor发明原创视频(http:// vimeo.com/36579366)的启发.

此外,我非常着迷于使用Javascript绘制的树.我没有做太多的图形编程.我所有的职业生涯都是一个中间层和数据库开发人员.但是通过编程方式来绘制树,我有动力去学习.我已经开始学习Javascript了.我知道我会最终(在几个星期或几个月,取决于我获得多少时间)能够从头开始写这样的程序.

然而,我真的很想得到一些源代码,它在Javascript中做类似的绘图,并与之一起玩.你们可以提供的任何链接/指针将是非常有用的.

解决方法

用画布画一棵树就够简单了.请参阅下面的约80行代码解决方案.

有几个人开始尝试从视频重新创建互动环境. One of those attempts是由github user tnlogy制作的.他的环境允许您在代码中选择一个数字,并使用滑块即时更改正在运行的演示.我已经把他的代码分成了一个树示范.

互动树演示:

http://brianpeiris.github.com/live-coding/

简单树演示:

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,Math.PI * 2);
    cx.fill();
  },drawBranch = function (ii,cx,level,levels,angle,numBranches) {
    var
      branchLength = 44,subBranchWidthFactor = 2,sweep = Math.PI * 25/30,branchTweakMagnitude = 52/50,tt;

    cx.beginPath();

    // Draw thinner branches away from the trunk
    cx.lineWidth = (levels - level) * subBranchWidthFactor;

    // Calculate the angle of the branch,with some random tweaks
    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();

    // Recursively draw more branches
    drawBranchesAndLeaves(cx,newXX,newYY,level + 1,Math.PI + tt);
  },drawBranchesAndLeaves = function (cx,angle) {
    var
      numBranches = 5,ii,newXY;

    // This function is called recursively. The recursion terminates when we
    // have reached the specified number of recursive levels.
    if (level === levels) { 
      drawLeaf(cx,yy);
      return; 
    }
    else {
      for (ii = 0; ii < numBranches; ii++) {
        drawBranch(ii,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,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);
原文链接:/js/151298.html

猜你在找的JavaScript相关文章