Contributed by Chris Rathman
<HTML>
<HEAD>
<TITLE>Javascript Shapes</TITLE>
<SCRIPT LANGUAGE='JavaScript'>
<!--
function Shape(initx, inity) {
// declare and initialize x & y coordinates
this.x = initx;
this.y = inity;
// accessors for x & y coordinates
this.getX = new Function('return(this.x);');
this.getY = new Function('return(this.y);');
this.setX = new Function('newx', 'this.x = newx;');
this.setY = new Function('newy', 'this.y = newy;');
// modify the shape coordinates
this.moveTo = new Function('newx', 'newy',
'{ this.setX(newx); this.setY(newy); }');
this.rMoveTo = new Function('newx', 'newy',
'this.moveTo(newx + this.getX(), newy + this.getY());');
}
function Rectangle(initx, inity, initwidth, initheight) {
// inherit attributes and methods from shape class
this.base = Shape;
this.base(initx, inity);
// declare and initialize width & height
this.width = initwidth;
this.height = initheight;
// accessors for width & height
this.getWidth = new Function('return(this.width);');
this.getHeight = new Function('return(this.height);');
this.setWidth = new Function('newwidth', 'this.width = newwidth;');
this.setHeight = new Function('newheight', 'this.height = newheight;');
// draw the rectangle (set to defined function)
this.draw = drawRectangle;
}
function drawRectangle() {
document.writeln('Drawing a Rectangle at:(' + this.getX() + ',' + this.getY() +
'), width ' + this.getWidth() + ', height ' + this.getHeight() + '<BR>');
}
function Circle(initx, inity, initradius) {
// inherit attributes and methods from shape class
this.base = Shape;
this.base(initx, inity);
// declare and initialize radius
this.radius = initradius;
// accessors for radius
this.getRadius = new Function('return(this.radius);');
this.setRadius = new Function('newradius', 'this.radius = newradius;');
// draw the circle (set to defined function)
this.draw = drawCircle;
}
function drawCircle() {
document.writeln('Drawing a Circle at:(' + this.getX() + ',' + this.getY() +
'), radius ' + this.getRadius() + '<BR>');
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE='JavaScript'>
<!--
// set up array with some shape instances
scribble = new Array(2);
scribble[0] = new Rectangle(10, 20, 5, 6);
scribble[1] = new Circle(15, 25, 8);
// iterate through the shapes
for (j = 0; j < scribble.length; j++) {
scribble[j].draw();
scribble[j].rMoveTo(100, 100);
scribble[j].draw();
}
// access a rectangle specific function
arectangle = new Rectangle(0, 0, 15, 15);
arectangle.setWidth(30);
arectangle.draw();
//-->
</SCRIPT>
</BODY>
</HTML>
Drawing a Rectangle at:(10,20), width 5, height 6 Drawing a Rectangle at:(110,120), width 5, height 6 Drawing a Circle at:(15,25), radius 8 Drawing a Circle at:(115,125), radius 8 Drawing a Rectangle at:(0,0), width 30, height 15