- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
Drawing a Rectangle in Javascript - part 1 in a series
Why drawing a rectangle is interesting
Computer programming constantly uses encapsulation; someone else figures out how to do something, and you just use it without having to worry about the details. Functions are one mechanism for encapsulation, which is the important concept I want to communicate.
The Javascript function, drawrectangle(), in the example below, encapsulates the mechanics of drawing a rectangle. You could copy the text from the code example, paste it into an HTML file, and open that file from your browser. You should see one black rectangle, and one dot.
Next, you can edit the lines reading:
drawrectangle( "blackrectangle", 50, 50, 10, 100 ); // draw a black rectangle on top
-AND-
drawrectangle( "blackrectangle", 50, 100, 1, 1 ); // draw a dot (pixel)
to draw rectangles in whatever positions and sizes you want. You don't have to worry about how this function is implemented, just that it takes the coordinates of the upper left hand corner of a rectangle and the rectangle's width and height as parameters. Don't change anything else in these lines, just the numbers, and see what happens when you save your edits and reload the file from your browser.
In later hubs, I will give examples of how to use this function to draw more complex shapes.
The html file
<html> <head> <style type="text/css" > .whiterectangle { color: white; background-color: white; z-index: 0;} .blackrectangle { color: black; background-color: black; z-index: 1;} </style> <script type="text/javascript" > function drawrectangle( myclass, top, left, width, height ) { var bodylist = document.getElementsByTagName( "body" ); var rect = document.createElement( "div" ); var mystyle = 'position:absolute;top:' + top + ";left:" + left + ';width:' + width + ";height:" + height; rect.setAttribute( "class", myclass ); rect.setAttribute( "style", mystyle ); bodylist[0].appendChild( rect ); } </script> </head> <body> <script type="text/javascript" > drawrectangle( "whiterectangle", 0, 0, "100%", "100%" ); // make a background rectangle, not necessary with default browser settings drawrectangle( "blackrectangle", 50, 50, 10, 100 ); // draw a black rectangle on top drawrectangle( "blackrectangle", 50, 100, 1, 1 ); // draw a dot (pixel) </script> </body> </html>
Drawing a rectangle caught in Firebug
for further study
- JavaScript Tutorial
Free HTML XHTML CSS JavaScript DHTML XML DOM XSL XSLT RSS AJAX ASP ADO PHP SQL tutorials, references, examples for web building. - CSS Tutorial
Free HTML XHTML CSS JavaScript DHTML XML DOM XSL XSLT RSS AJAX ASP ADO PHP SQL tutorials, references, examples for web building.