HTML and CSS Reference
In-Depth Information
Figure 3.29 shows the end result.
Stepping through the code you will see that the CANVAS ele-
ment has not changed. What is modified is how the object in the
CANVAS element is presented. Using JavaScript, you start a new
function named “draw.” The draw function is constructed of a
variable called “myCanvas” . The “myCanvas” variable declares
that the CANVAS element is a 2D object. The distinction of 2D is
important, as it is expected that a three-dimensional (3D) defini-
tion will be added to the CANVAS element as part of the WebGL
3D program.
You use Cascading Style Sheets to define the color and border
thickness for the drawing. In this instance, the drawing is black
with a solid 1-pixel outline.
The “onload” event in the BODY element triggers when the
CANVAS illustration is drawn.
Figure 3.29 The CANVAS
element draws a simple rectangle.
Controlling Shapes
The CANVAS element does not have the same rich collection
of primitive drawing objects you find in SVG. The only primitive
drawing object is a rectangle. This does not limit what you can
draw, as CANVAS leverages an alternative, rich collection of path
drawing functions that allow you to create complex paths, arcs,
Bezier curves, and quadratic curves that you can use as the basis
of your illustrations.
The rectangle shape is built of four basic parts:
• X—startingpositionoftherectanglealongtheXaxis
• Y—startingpositionoftherectanglealongtheYaxis
• Width—widthoftherectangle
• Height—heightoftherectangle
The following is an example of a solid rectangle shape:
myRectangle.fillRect(15,15,100,100);
This description places the rectangle as starting 15 pixels in
from the left side of the CANVAS element (the X axis), 15 pix-
els from the top of the CANVAS element (the Y axis), and with a
width and height of 100 pixels each. You need to add the follow-
ing HTML to view the rectangle.
<html>
<head>
<title>Basic Canvas Drawing</title>
<script>
function draw(){
var canvas = document.getElementById
('myCanvas');
if (canvas.getContext){
Search WWH ::




Custom Search