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.
3.129.19.251