Book Image

HTML5 Canvas Cookbook

By : Eric Rowell
Book Image

HTML5 Canvas Cookbook

By: Eric Rowell

Overview of this book

The HTML5 canvas is revolutionizing graphics and visualizations on the Web. Powered by JavaScript, the HTML5 Canvas API enables web developers to create visualizations and animations right in the browser without Flash. Although the HTML5 Canvas is quickly becoming the standard for online graphics and interactivity, many developers fail to exercise all of the features that this powerful technology has to offer.The HTML5 Canvas Cookbook begins by covering the basics of the HTML5 Canvas API and then progresses by providing advanced techniques for handling features not directly supported by the API such as animation and canvas interactivity. It winds up by providing detailed templates for a few of the most common HTML5 canvas applications—data visualization, game development, and 3D modeling. It will acquaint you with interesting topics such as fractals, animation, physics, color models, and matrix mathematics. By the end of this book, you will have a solid understanding of the HTML5 Canvas API and a toolbox of techniques for creating any type of HTML5 Canvas application, limited only by the extent of your imagination.
Table of Contents (19 chapters)
HTML5 Canvas Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Canvas Security
Index

Unlocking the power of fractals: Drawing a haunted tree


First thing's first—what are fractals? If you don't already know, fractals are the awesome result when you mix mathematics with art, and can be found in all sorts of patterns that make up life. Algorithmically, a fractal is based on an equation that undergoes recursion. In this recipe, we'll create an organic-looking tree by drawing a trunk which forks into two branches, and then draw two more branches that stem from the branches we just drew. After twelve iterations, we'll end up with an elaborate, seemingly chaotic mesh of branches and twigs.

How to do it...

Follow these steps to draw a tree using fractals:

  1. Create a recursive function that draws a single branch that forks out into two branches, and then recursively calls itself to draw another two branches from the end points of the forked branches:

    function drawBranches(context, startX, startY, trunkWidth, level){
        if (level < 12) {
            var changeX = 100 / (level + 1);
            var changeY = 200 / (level + 1);
            
            var topRightX = startX + Math.random() * changeX;
            var topRightY = startY - Math.random() * changeY;
            
            var topLeftX = startX - Math.random() * changeX;
            var topLeftY = startY - Math.random() * changeY;
            // draw right branch
            context.beginPath();
            context.moveTo(startX + trunkWidth / 4, startY);
            context.quadraticCurveTo(startX + trunkWidth / 4, startY - trunkWidth, topRightX, topRightY);
            context.lineWidth = trunkWidth;
            context.lineCap = "round";
            context.stroke();
            
            // draw left branch
            context.beginPath();
            context.moveTo(startX - trunkWidth / 4, startY);
            context.quadraticCurveTo(startX - trunkWidth / 4, startY -
            trunkWidth, topLeftX, topLeftY);
            context.lineWidth = trunkWidth;
            context.lineCap = "round";
            context.stroke();
            
            drawBranches(context, topRightX, topRightY, trunkWidth * 0.7, level + 1);
            drawBranches(context, topLeftX, topLeftY, trunkWidth * 0.7, level + 1);
        }
    }
  2. Initialize the canvas context and begin drawing the tree fractal by calling drawBranches():

    window.onload = function(){
        canvas = document.getElementById("myCanvas");
        context = canvas.getContext("2d");
        
        drawBranches(context, canvas.width / 2, canvas.height, 50, 0);
    };
  3. Embed the canvas tag inside the body of the HTML document:

    <canvas id="myCanvas" width="600" height="500" style="border:1px solid black;">
    </canvas>

How it works...

To create a tree using fractals, we need to design the recursive function that defines the mathematical nature of a tree. If you take a moment and study a tree (they are quite beautiful if you think about it), you'll notice that each branch forks into smaller branches. In turn, those branches fork into even smaller branches, and so on. This means that our recursive function should draw a single branch that forks into two branches, and then recursively calls itself to draw another two branches that stem from the two branches we just drew.

Now that we have a plan for creating our fractal, we can implement it using the HTML5 canvas API. The easiest way to draw a branch that forks into two branches is by drawing two Quadratic curves that bend outwards from one another.

If we were to use the exact same drawing procedure for each iteration, our tree would be perfectly symmetrical and quite uninteresting. To help make our tree look more natural, we can introduce random variables that offset the ending points of each branch.

There's more...

The fun thing about this recipe is that every tree is different. If you code this one up for yourself and continuously refresh your browser, you'll see that every tree formation is completely unique. You might also be interested in tweaking the branch-drawing algorithm to create different kinds of trees, or even draw leaves at the tips of the smallest branches.

Some other great examples of fractals can be found in sea shells, snowflakes, feathers, plant life, crystals, mountains, rivers, and lightning.