spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / gr / column2 / 1 current pageTo page 2
[next]

Sr. Programmer/Analyst
Professional Technical Resources
US-OR-Portland

Justtechjobs.com Post A Job | Post A Resume
Developer News
Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next

JavaScript OO Vector Graphics Package

Over the years, JavaScript has developed into the browser scripting language of choice for DHTML. It has complete access to the browser’s Document Object Model (DOM) and Cascading Style Sheets (CSS). One apparent omission from JavaScript’s functionality seemed to be the ability to draw graphics directly to the browser window. When this was questioned the answer was always along the lines of “JavaScript is intended to provide DHTML in browsers and is not suited for CPU intensive operations like graphics.”

However, there are benefits when using JavaScript to create an extensible object-oriented vector-based graphics package. Some of these are:

  • JavaScript is widely supported in browsers and fairly well standardized.


  • Easy integration with other JavaScript code.


  • The JavaScript graphics is drawn in the same browser windowpane as other HTML elements. This differs from technologies such as Java and Flash where on Windows plat forms at least the output is contained within a separate windowpane and will always obscure any HTML below.
The first step in building a graphics framework is to specify the canvas (the space in which to display the graphics). For this we choose the HTML <DIV> tag, or if none specified the <BODY> tag. If using a <DIV>, it must have a style attribute specifying position to either absolute or relative. For example:

<HTML>
   <BODY>
      <DIV id=”theCanvas” style=”position:absolute; left=100px;    top=50px;”>
      </DIV>
   </BODY>
</HTML>

Now, with a canvas to render on we can start building the graphics framework. The framework must oversee interactions with the canvas providing the ability to “plot” points, and it will also hold all the attributes which will affect the drawing such as the pen color, z-index and so on.

The framework is managed by a class called “Graphics” which supports a minimal core set of functions. The constructor takes the id of the canvas or “” or null for the <BODY> and initializes the framework variables and settings.

function Graphics(canvas) 
{ 
   // the ID of the canvas DIV or “” for document.body
   this.canvas = canvas;
   // a cache of hidden DIV elements
   this.cache = new Array; 
   // the collection of displayed shapes
   this.shapes = new Object; 
   // a number used for generating internal IDs
   this.nObject = 0; 
   
   // default settings
   this.penColor = "black";
   this.zIndex = 0; 
}

Plots are implemented by creating small pixel-sized <DIV> elements contained and positioned within the parent canvas. The createPlotElement() method of the Graphics class handles this task. It first checks the reference to the canvas. If not previously retrieved, it finds it using document.getElementById(), or document.body if no ID is supplied. Next it gets a <DIV> element for the new pixel either from the cache or by creating a new one and appends it to the canvas. New <DIV> elements must have their style.position attribute set to absolute so that they may be positioned within their parent canvas. Finally, the graphics settings are applied to the plot element along with its position and size.

Graphics.prototype.createPlotElement = function(x,y,w,h) 
{
   // detect canvas
   if ( !this.oCanvas )
   {
      if ( (this.canvas == undefined) || (this.canvas == "") ) 
          this.oCanvas = document.body;
      else 
         this.oCanvas = document.getElementById(this.canvas);
   }
 // retrieve DIV
 var oDiv;
 if ( this.cache.length )
   oDiv = this.cache.pop();
 else {
   oDiv = document.createElement('div');
   this.oCanvas.appendChild(oDiv);
   oDiv.style.position = "absolute";
   oDiv.style.margin = "0px";
   oDiv.style.padding = "0px";
   oDiv.style.overflow = "hidden";
   oDiv.style.border = "0px";
 }
 // set attributes
 oDiv.style.zIndex = this.zIndex;
 oDiv.style.backgroundColor = this.penColor;
   
   oDiv.style.left = x;
   oDiv.style.top = y;
   oDiv.style.width = w + "px";
   oDiv.style.height = h + "px";
   oDiv.style.visibility = "visible";
   
   return oDiv;
}


Plot-elements are released and “un-plotted” using the releasePlotElement() method. This method simply sets the style.visibility attribute of the <DIV> element to “hidden” and places it in the cache for later reuse.

Everything drawn on the canvas must be managed by Shape objects. The “Shape” within the graphics framework is an abstract term referring to JavaScript classes that support draw() and undraw() methods. The Shape object provides a convenient handle to group plot-elements together and can be arbitrarily complex. To manage shapes within the framework we need the following two methods in the Graphics class.

Graphics.prototype.addShape = function(shape) 
{
   shape.oGraphics = this;
   shape.graphicsID = this.nObject;
   this.shapes[this.nObject] = shape;
   this.nObject++;
   shape.draw();
   return shape;
}
Graphics.prototype.removeShape = function(shape) 
{
   if ( (shape instanceof Object) && 
      (shape.oGraphics == this) && 
      (this.shapes[shape.graphicsID] == shape) ) 
   {
      shape.undraw();
      this.shapes[shape.graphicsID] = undefined;
      shape.oGraphics = undefined;
   }
}
The addShape() method sets two properties on the supplied shape object; the oGraphics property is set to the instance of the Graphics class and the graphicsID is set to a unique number. This graphicsID is used to access the shape later. Finally, the draw() method is called on the shape causing it to render itself on the canvas.

The removeShape() method checks that the supplied shape is contained within the canvas, then calls undraw() to allow the shape to release its plot-elements before clearing the it from the collection of shapes.

home / programming / javascript / gr / column2 / 1 current pageTo page 2
[next]



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview · Controllers: Programming Application Logic - Part 2 · How to Use JavaScript to Validate Form Data
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Choosing the Right Online Backup Provider · Mother Avaya Nurtures Her Technology Partners · Software as a Service a Winning Model for Hotspot Provider

Created: June 5, 2003
Revised: January 14, 2004

URL: http://webreference.com/programming/javascript/jf/1