How to Set Up the JavaScript Canvas for HTML5 and CSS3 Programming

To use the <canvas> tag in JavaScript, build an HTML5 and CSS3 web page with a <canvas> element in it to begin. Typically you'll provide width, height, and id parameters:

 <canvas id = "drawing"
   width = "200"
   height = "200">
 <p>Your browser does not support the canvas tag...</p>
 </canvas>

Inside the <canvas> tag, you can put any HTML code you wish. This code will appear if the browser does not support the <canvas> tag. Typically, you'll just put some sort of message letting the user know what she's missing.

Nothing interesting happens in a canvas without some kind of JavaScript code. Often you'll use a function to draw on the screen. Here's a draw() function, which is called by the body onload event:

image0.jpg
 function draw(){
 //from basicCanvas.html
 var canvas = document.getElementById("drawing");
 if (canvas.getContext){
  var con = canvas.getContext('2d');
  con.fillStyle = "#FF0000";
  con.fillRect(10, 10, 50, 50);
 } // end if
 } // end draw

The draw() function illustrates all of the main ideas of working with the canvas tag. Here's how you build a basic drawing:

  • Create a variable reference to the canvas: Use the standard getElementById() mechanism to create a variable referring to the canvas.

  • Extract the graphics context from the canvas: Canvas elements have a graphics context, which is a special object that encapsulates all the drawing methods the canvas can perform. Most browsers support a 2D context now, but 3D contexts are beginning to appear as well.

  • Set the context's fillStyle: The fillStyle indicates how you will color filled-in areas (like rectangles). The basic approach is to supply a CSS color value.

  • Create a filled-in rectangle: The graphics context has a few built-in shapes. The rectangle shape is pretty easy to build. It expects four parameters: x, y, width, and height. The x and y parameters indicate the position of the rectangle's top left corner, and the height and width parameters indicate the size of the rectangle. All measurements are in pixels.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com