Time for action – creating a canvas pad

You can find the source code for this section at chapter4/example4.1. Let's start by copying our application template that we created in the first chapter and renaming the file names to canvasPad.html, canvasPad.css, and canvasPad.js. Then we'll go in and change the links in the HTML for those files. Finally we change the main application object in the JavaScript to CanvasPadApp.

Now let's add a <canvas> element to the HTML right inside the <div id="main"> element and size it to 600 by 400:

<div id="main">
  <canvas width="600" height="400">
    Sorry, your browser doesn't support canvas.
  </canvas>
</div>

Next we'll add some styles to the CSS to center the canvas on the page and give it a white background. We'll also use a box-shadow element to make it stand out:

#main
{
    text-align: center;
}
#main>canvas
{
    cursor: crosshair;
    margin: 1em auto;
    background-color: white;
    box-shadow: 0 0 8px 2px #555;
}

In order to encapsulate our interaction with the canvas we are going to create a new object called Canvas2D and put it in a file named canvas2d.js. In this object we will create some higher level drawing functions. This object's constructor takes a <canvas> element wrapped in a jQuery object as a parameter:

function Canvas2D($canvas)
{
    var context = $canvas[0].getContext("2d"),
        width = $canvas[0].width,
        height = $canvas[0].height;
}

The first thing the constructor does is set some private variables. We get the context, width, and height from the $canvas jQuery object.

Note

You can get access to the underlying element that a jQuery object wraps by using square brackets such as an array. So in this case $canvas[0] gives us the first (and only) <canvas> element.

What just happened?

We created a new canvas pad application from our template and added a canvas to it. We centered the canvas on the page and gave it an all-over shadow to frame it and make it appear to float on top of the page. Finally, we created a Canvas2D object to encapsulate interaction with the canvas.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.19.251