CVTree

A Canvas CV Tree

by GertG

HTML

<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<p><canvas class="tree" width="800" height="400" /></p>

JavaScript

(function() {

    var requestAnimationFrame = (function() {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback, element) {
            window.setTimeout(callback, 1000 / 16);
        };
    })();

		var branches = [];
    var canvas;
    
    $(function() {
				canvas = $('canvas.tree')[0];
				branches.push({
        	thickness: 20,
          origin: {
          	x: canvas.width / 2,
            y: canvas.height - 40
          },
          tip: {
          	x: canvas.width / 2,
            y: canvas.height - 140
          }
        });

        canvas = $('canvas.tree')[0];
        ctx = canvas.getContext('2d');



        loop();
    });
    
    function loop(onFrame) {

        update();
        draw(ctx);
        
        requestAnimationFrame(loop);
    }
    
    function update(){
    
    }

    function draw(){
    	//console.log('draw');
        ctx.fillStyle = 'rgb(0,0,0)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        drawBranch(branches[0]);
    }	
    
    function drawBranch(branch) {
            var w = branch.thickness;
            var oX1 = branch.origin.x - w;
            var oX2 = branch.origin.x + w;
            var oY = branch.origin.y;
            var tX1 = branch.tip.x - w * 0.8;
            var tX2 = branch.tip.x + w * 0.8;
            var tY = branch.tip.y;
            var cpX1 = (oX1 + oX1 + tX1) / 3;
            var cpY1 = (oY + tY + tY) / 3;
            var cpX2 = (oX2 + oX2 + tX2) / 3;
            var cpY2 = (oY + tY + tY) / 3;
            ctx.beginPath();
            ctx.moveTo(oX1, oY);
            ctx.quadraticCurveTo(cpX1, cpY1, tX1, tY);
            ctx.lineTo(tX2, tY);
            ctx.quadraticCurveTo(cpX2, cpY2, oX2, oY);
            ctx.lineWidth = 1;
            ctx.fillStyle = "#FF0000";
            ctx.fill();
        }
}());