HTML and CSS Reference
In-Depth Information
You can find this file among the topic's downloadable files (available from www.apress.com) as 01-
drawing-app.html . In addition to the drawing functions, this program makes good use of event handlers
(discussed in Chapter 2). Let's go through it piece by piece.
The example is based on the skeleton document found in Chapter 2, which you should be used to by now.
At the top of the script, it uses the utility function utils.captureMouse to keep track of the mouse
position. We imported this from the file utils.js . Event listeners for the mousedown and mouseup events
are also added.
The mousedown event handler gets called whenever the user presses a mouse button on the canvas
element; this is when the user wants to start drawing a line at the current mouse cursor position. The
handler starts a new path and puts the virtual pen down at the mouse location by calling context.moveTo
and passing in the mouse coordinates. It then adds a listener for the mousemove event.
At this point, every time the user moves the mouse, the onMouseMove function is called. It's the core of the
program, but is simple. It draws a line to the current mouse location and strokes the path outline.
Finally, there's the mouseup event handler, which removes the mousemove handler so that nothing else is
drawn to the canvas.
This is a fun little sketching program. If you set up some simple controls, you can build it into a full-featured
drawing application. Create variables for color and width , use some HTML form elements to change
them, and set the strokeStyle and lineWidth properties with the new values. But this left as an
exercise for you to do on your own, if you are interested.
Drawing curves with quadraticCurveTo
The canvas drawing API provides a number of methods for drawing curves on a path. In the next couple of
examples, we look at the method context.quadraticCurveTo , which connects two points with a curve
using a control point. It starts off the same as context.lineTo , in that it begins its drawing at the point
where the last drawing ended, or at the point where the last context.moveTo command moved the pen
to. It also uses line styles in the same way as context.lineTo . The only difference is the shape of the
line drawn.
context.quadraticCurveTo(cpx, cpy, x, y) takes two points as arguments: The first is a control
point that affects the shape of the curve, and the second is the ending point of the curve. The shape is
determined by a standard algorithm known as a quadratic Bézier curve . This function calculates a curve
from one point to another, curving toward—but never touching—the control point. It's more like the curve is
attracted to it.
Let's see it in action in the following document, 02-drawing-curves.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drawing Curves</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
 
Search WWH ::




Custom Search