Drawing Basic Patterns In Canvas

Begin with drawing a simple rectangular blue box like this: 

        function drawScreen() {
            context.save();
            drawPattern();
            context.restore();
        }

        function drawPattern() {
            context.fillStyle = “blue”; //
            var i = 0, x = 5, y = 0;
            context.fillRect(x, y, 20, 20);
        }

 Multiply the box:

        function drawPattern() {

            context.fillStyle = “blue”; //

            var i = 0, x = 5, y = 0;

            context.fillRect(x, y, 20, 20);

            for (i; i < 100; i++) {                

                context.translate(5, 0);

                x = x + 5;

                context.fillRect(x, y, 20, 20);

            }

        }

Switch colors:

context.fillStyle = “green”; //

                if (isOdd(i)) {

                    context.fillStyle = “blue”; //

                }

Repeat pattern throughout the canvas:

function drawScreen() {

            var z = 0;

            for (z; z < canvas.height;) {

                context.save();

                context.translate(0, z);

                drawPattern();

                z = z + 10;

                context.restore();

            }

        }


More patterns you can get with some code manipulations:

 

Basic Setup for HTML Canvas

This is a basic setup for starting any project in HTML5 CANVAS and Javascript.
The script that is being used is Modernizer.js which is is a JavaScript library that detects HTML5 and CSS3 features in the user’s browser.

   

    Canvas Study

    http://modernizr.js

   

       

            Your browser does not support HTML5 Canvas.

       

   

    window.addEventListener(‘load’, eventWindowLoaded, false);

    function eventWindowLoaded() {

        canvasApp();

    }

    function canvasSupport() {

        return Modernizr.canvas;

    }

    function canvasApp() {

        if (!canvasSupport()) {

            return;

        } else {

            var theCanvas = document.getElementById(“canvas”);

            var context = theCanvas.getContext(“2d”);

        }

        drawScreen();

        function drawScreen() {

            context.font = ’20px _sans’;

            context.textBaseline = ‘top’;

            context.fillText(“Canvas!”, 0, 0);

        }

    }

This code should produce a page that outputs the text “Canvas!” in a canvas with white background.