Paint Brush App for Html

by Pratik Bhoir

HTML

<button onclick="drawingApp.erase();">Clear</button>
<div id="canvasDiv"></div>For more Info <a href="http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/">Click Here</a>

JavaScript

var drawingApp = (function () {
    //declaring Variables
    var canvas,
        canvasDiv,
        context,
        canvasWidth = 200,
        canvasHeight = 200,
        clickX = [],
        clickY = [],
        clickDrag = [],
        paint = false;

    //Initalisation Function
    function init() {
        canvasDiv = document.getElementById('canvasDiv');
        canvas = document.createElement('canvas');
        canvas.setAttribute('width', canvasWidth);
        canvas.setAttribute('height', canvasHeight);
        canvas.setAttribute('id', 'canvas');
        canvasDiv.appendChild(canvas);
        if (typeof G_vmlCanvasManager != 'undefined') {
            canvas = G_vmlCanvasManager.initElement(canvas);
        }
        context = canvas.getContext("2d");
        loadEvents(); //Load events
    }

    function loadEvents() {
        //Mouse down Event
        $('#canvas').mousedown(function (e) {
            var mouseX = e.pageX - this.offsetLeft;
            var mouseY = e.pageY - this.offsetTop;

            paint = true;
            addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
            redraw();
        });

        //Mouse Move Event
        $('#canvas').mousemove(function (e) {
            if (paint) {
                addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
                redraw();
            }
        });

        //Mouse Up Event
        $('#canvas').mouseup(function (e) {
            paint = false;
        });

        //Mouse Leave Event
        $('#canvas').mouseleave(function (e) {
            paint = false;
        });

    }

    //Add Click Function
    function addClick(x, y, dragging) {
        clickX.push(x);
        clickY.push(y);
        clickDrag.push(dragging);
    }

    //Redraw Function
    function redraw() {
        context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas

        context.strokeStyle = "#df4b26";
        context.lineJoin =...