HTML5 Canvas Control - Capturing Mouse Motion

Fiddle exploring how to create a simple drawing interface using a canvas control.

by brady houseknecht

HTML

<div class="page-header">
     <h3>&nbsp;&nbsp;Canvas Mouse Plotting</h3>

</div>
<div class="container enter-stage-south">
    <div class="row">"Click and Drag" the mouse to create a drawing.
        <br />
        <br />
    </div>
    <div class="row">
        <canvas id="fiddleHook" width="300" height="300" style="background-color:#ffffff; cursor: default; width:300px;height:300px;border:1px solid black;"></canvas>
    </div>
    <div class="row">
        <input type="button" value="clear" id="btnClear">
    </div>
</div>

CSS

.enter-stage-south {
    -moz-animation-duration: 3s;
    -webkit-animation-duration: 3s;
    -moz-animation-name: slide-up;
    -webkit-animation-name: slide-up;
}
@-moz-keyframes slide-up {
    from {
        margin-top: 100%;
    }
    to {
        margin-top: 0%;
    }
}
@-webkit-keyframes slide-up {
    from {
        margin-top: 100%;
    }
    to {
        margin-top: 0%;
    }
}

JavaScript

(function (app, $, undefined) {

    $(document).ready(function () {
        console.log('document ready');
        $("#fiddleHook").on("mousemove", app.onCanvasMouseMove);
        $("#btnClear").on("click", app.onButtonClearClick);
    });

    app.onCanvasMouseMove = function (e) {
        if (e.which === 1) {
            var c = document.getElementById("fiddleHook"),
                ctx = c.getContext("2d"),
                rect = c.getBoundingClientRect(),
                x = e.clientX - rect.left,
                y = e.clientY - rect.top;
            ctx.fillRect(x, y, 8, 6);

        }
    }

    app.onButtonClearClick = function (ctrl) {
        var c = document.getElementById("fiddleHook"),
            ctx = c.getContext('2d');
        ctx.clearRect(0, 0, c.width, c.height);
    }


})(window.app = window.app || {}, jQuery)