Professional Documents
Culture Documents
Computer Aided Design (CAD) has been around since the early 1960’s to facilitate the
design of objects through computers. It is an extensive field that’s nestled in the spectrum
of Automated Methods (see fig.1) and often associated with other fields in this spectrum,
such as CAM (Computer Aided Manufacturing) or CAE (Computer Aided Engineering).
The definition of CAD is "the integration of computer science methods and engineering
sciences in a computer-based system, providing a database, a program library, and a
communication subsystem (Barr)." In less complicated terms, CAD process of design
with the support of a CAD system. Thus, in order to understand CAD, we must first delve
into the process of design.
The design process differs depending on the product, company’s or organization’s size,
and on the type of design. Obviously, there will be a difference in process between
designing a bicycle based on previous models for a private company and designing a
completely new and original blueprint of a nuclear power plant for the government.
Below are the bare basics of the design process:
1. Conceptualization stage (product planning) - sketch the ideas to guide the design;
outcome is the preliminary/conceptual model
4. Evaluation of the design’s performance - based on the results of step (3), make
sure there are no violations in product requirements
5. Modification of the design model to improve its performance (if any violations
occur)
is the Computer Aided Design comes into play when the designer uses computers as the
primary tool to carry out the above eight steps, as opposed to pen and paper:
1. In the first step of design process, the conceptualization stage, the designer can
enter the ideas into a computer. The CAD program will then transform the data
into a computer model. The computer not only stores the data at this stage, but
also responds to it by guiding the designer on how to better his/her ideas through
access of its vast knowledge base.
2. During the second step, the designer can once again make use of the large
databases of previous designs, standard codes of practices, handbooks, and other
resources to help him in his decision making. The computer keeps track of design
dependency (if one value is changed, then all the other values that depend on it
are automatically changed accordingly), making the manipulation of size and
proportionality much quicker and easier.
3. In the analysis stage, the computer can easily run the tests and numerical
computations.
4. The computer then evaluates the results from these tests with the designer to...
7. Once again, the large stores of databases and knowledge based programs come
into play. These stores of information and the computer’s advanced graphic
capability aid the designer in the process of detailed design.
8. A plotter carries out the last step, printing the finished drafts. In CAD/CAM
systems, the design data can be stored in special machine-controlled tapes and
disks in digitized form. Machine tools can then read these tapes/disks and
manufacture the product designed.
Hopefully, you now know how computers come into play with the design process. The
next step to grasping the concept of CAD is learning its pros and cons.
The biggest and most important advantage of CAD is:
increase in productivity
enabling designs analysis in various angles, sizes, and cross-sections (an object
can be sliced to reveal its internal structure)
decrease in expenses
flexibility
The disadvantages listed below can be alleviated with lots of experience and a good
working knowledge of a programming language such as C and Pascal:
a computer can only carry out systematic reasoning (which is limited to the
programs stored). It has no creative skills, imagination, or judgement to generate
ideas like the designer.
Because of its advantages and disadvantages, the design process is sometimes best
implemented with a combination of manual design and CAD supported design. This
combination of design is known as full-custom design. An example of a product that is
usually designed in this fashion is the microprocessor chip.
CAD can be used in almost all fields of engineering. Three major engineering
fields that rely heavily on CAD are:
electrical
architectural
mechanical
Electrical engineering
The first application of CAD was in the electronics industry. With the increasing
complexity of electronic devices, computers have become imperative inelectrical design.
Integrated circuits (ICs) are a good example of this developed dependency on CAD. Each
integrated circuit used to have less then thirty transistors and a thousand geometries
(geometric patterns). Now, these numbers have risen drastically. With over one million
transistors and ten million geometries per IC, the conventional method of design is no
longer an option.
Advantages
Electrical designs "present a mathematically indeterminate problem" (Hamdi). There is
no single optimum design, but several different ways to solve the design problem. With
the advent of CAD, electrical engineers have a quick and easy access to alternate designs.
Another function that CAD programs offer is validating the circuits and the accuracy of
the design. If, for instance, an attempt to design a bistable circuit is made, the CAD
program will check that the values attributed to the various components will produce the
desired circuit. Faulty permanent magnet design used to pose as a big threat to electrical
engineers because it resulted in partial demagnetization, but because of CAD’s ability to
verify the reasonability of the design, it's no longer a problem. Other basic advantages
offered by CAD in electrical engineering are
testing done on the design (such as the maximum value of load resistance the
design can support).
Approaches to CAD
There are two basic approaches to designing electrical machines with CAD:
1. analysis method
2. synthesis method
Analysis method
In the analysis method, information such as the dimension, the material being used, and
type of construction involved are inputted into the computer. With this information, the
computer can run several tests and calculations on the characteristics of the design. After
analyzing the results, the design is altered and the steps are repeated until the
specifications are met.
Synthesis method
The only difference between the analysis method and the synthesis method is the initial
step. The synthesis method assumes that the CAD software includes the design procedure
and a data library filled with information on various materials. The initial design (which,
many times, is produced by the CAD system) is written in the computer program as
statements.
The finite element method included in the electrical engineering CAD packages allows
the analysis of different geometries and operating conditions through a simple data
structure instead of having to construct a time-consuming physical model. With a finite
element model, the engineer can certify, with a high accuracy, important design criteria
such as
flux linkages
induced voltages
core losses
winding inductance
Graphics
Numerical models are a major part of the electrical engineering design process, but the
importance of graphical models should not be overlooked. After all the computations are
completed, the information must be presented in a form that is easy to interpret and
analyze. Graphs and other graphic devices are the obvious and best solutions. Automation
can also help avoid some arduous operations. It is much simpler and quicker to indicate
with a graphic pen the part of the device where a reading (such as its flux density) is
wanted instead of having to first find the coordinates for that location.
Although all the electrical devices are three dimensional, they are often designed (for
convenience) in two dimensions and, less frequently, in one dimension. Not all designs
are reduced in dimensions though. In some cases, it is necessary to view the electrical
device in 3D in order to keep the accuracy of the design.
Architecture
give a competitive edge (many clients look for CAD abilities when hiring an
architect.)
With its introduction, CAD quickly moved up in status from being desirable to becoming
required in the field of Architecture.
click here for an example of a building designed with the support of CAD
are complete with the internal organization (such as the placement of furniture to
phones) of the building
often include animation, enabling the client to take a virtual tour of the building
inside and out.
geometric primitives
3D geometric modeling and viewing, usually wire frame and solid modelling.
Wire frame modelling, still widely used by architects, is known as the "ancestor
of contemporary CAD presentation". The nature of wire frame models reveals the
underlying structure of the building, thus helping architects check the project's
'buildability'. Due to this ability, wire frame modelling is used for establishing the
building's skeleton in the developmental design stages of most CAD programs.
Solid modelling is usually utilized for the finished model.
Despite wire frame modelling's advantages, some architects prefer using solid
modelling in the primary stages as well as in the final stage. The difference
between wire frames and solid modelling is parallel to the difference between
using paper/pencil and a 3D object like wood or foam to construct the initial
design. Even if solid modelling is used from beginning to end, the first draft does
not look remotely like the finished design. In the beginning stages, the architect is
not interested in making the building look realistic, only in outlining the rationale
of the design. Keith Williams of Pawson Williams Architect further explains how
CAD is used as an abstract design process by saying:
"The importance of the computer is as an interface between the physical design
and the abstract ideas behind it. We are interested in CAD as an architectural tool,
not as a tool for building."
It the later stage of design, realistic elements, like color, lighting, and shadows,
are added to help communicate the building design to the client.
Non-visuals
Visualization in Architecture is key, but it is not the only element involved in the
design stage. John Walker, founder of AutoCAD (one of the most widely used
CAD software among both architects and other design professionals), relays that a
true CAD program would be
"a system which describes physical objects and knows about the various ways in
which they interact."
Some non-visual questions that must be answered during the design process are
o what functions does the building have to perform (i.e. loads and stresses
the building must handle)
Mechanical engineering
A General Electric survey from a few years back found that over sixty percent of all
manufactured parts were not made according to the draft mainly due to
incomplete drawings
ambiguous drawings
The most common trait in a practical design problem is design object’s complexity. Some
designs are considered complex just due to sheer size. A pressure vessel designed to
withstand high pressures and thermal gradients is composed of 400 tons of steel in
material alone. Thus, it is not surprising that designers are continually pressured to
optimize their designs, especially in material use. Computer Aided Design
helps mechanical engineers try to solve the problem with optimum efficiency.
3D modelling
CAA consist of
Though CAG and CAA can be seen as two separate fields, they are intertwined in the
mechanical design process. CAA depends on CAG’s pre-processing and post-processing
skills. Likewise, CAG needs CAA’s analysis results to know how to modify the graphical
design. Design and analysis in general have become dependent on each other on account
of high-speed digital computers and methods (i.e., the finite element method) that relate
to the structural mechanics problem.
CAD analysis
As mentioned before, optimization is essential to help keep costs and time down. But
finding the most efficient procedure is no easy task, especially since most mechanical
CAD systems have to handle more then ten thousand unknowns. Breaking down the
design object into a set of simultaneous algebraic equations optimizes computational
labor in the analysis process. Some types of analysis performed on mechanical designs
and some possible characteristics they tests (according to Christopher McNulty
of Creative Products Group ) are:
The most important analyses of the four are the finite element and the finite difference
procedures. With these two methods, objects with complicated structures and loading (i.e.
static, dynamic, transient and random) can have their general behavioral characteristics
classified by three quantities:
1. stiffness
2. mass
3. damping
CAD graphics
The design structural geometry in mechanical engineering is complicated, not the
idealized uniform beams, plates, and shells. Thus, an advanced graphic modelling system
is needed. Most mechanical engineers use 3D solid modelling (the most complex form in
geometric modelling), and occasionally utilize surface modelling and two-dimensional
drafting. These graphics can be animated to show a machine, in full detail, in motion to
reveal how it will act in certain environments. This is especially useful in showing the
effects of various forces since the majority of forces acting on the machine devices vary
over time (such as stress). Some other advantages of CAD graphics in mechanical
engineering are:
Understand the basic principles and techniques used in computer aided design and
manufacture process.
Finishing the course students should have hands-on experience with 3D modeling and
design using available CAD/CAE tools.
Course Description
Course develops students' competence and self-confidence as design engineers. Emphasis
is on the creative design process.
Course covers design stages:
Design
Analysis
Rapid prototyping
Visualization and presentation
Planning and Manufacturing
2D Time[edit]
The first CAD systems served as mere replacements of drawing boards. The design
engineer still worked in 2D to create technical drawing consisting from 2D wireframe
primitives (line, arc, B spline ...). Productivity of design increased, but many argue that only
marginally due to overhead – design engineers had to learn how to use computers and CAD.
Nevertheless modifications and revisions were easier, and over time CAD software and
hardware became cheaper and affordable for mid size companies. CAD programs grew in
functionality and user friendliness. (1974)
This is 100% true that CAD first started off with using a sketch pad.
3D Time[edit]
3D wireframe features were developed in the beginning of the sixties, and in 1969 MAGI
released Syntha Vision, the first commercially available solid
modelerprogram. Solid modeling further enhanced the 3D capabilities of CAD
systems. NURBS, mathematical representation of freeform surfaces, appeared in 1989 --
first on Silicon Graphics workstations. In 1993 CAS Berlin developed an interactive NURBS
modeler for PCs, called NöRBS.
Parametric Design[edit]
In 1989 T-FLEX and later Pro/ENGINEER introduced CADs based on parametric engines.
Parametric modeling means that the model is defined by parameters. A change of dimension
values in one place also changes other dimensions to preserve relation of all elements in the
design.
(for example “this must be parallel with that and in the middle of
...”).
MCAD systems introduced the concept of constraints that enable you to define relations
between parts in assembly. Designers started to use a bottom-up approach when parts are
created first and then assembled together. Modeling is more intuitive, precise and later
analysis, especially kinematics easier.
Present[edit]
CAD/CAE/CAM systems are now widely accepted and used throughout the industry. These
systems moved from costly workstations based mainly on UNIX to off-the-shelf PCs. 3D
modeling has become a norm, and it can be found even in applications for the wider public,
like 3D buildings modeling in Google Maps, house furnishing (IMSI Floorplan), or garden
planning. Advanced analysis methods like FEM (Finite Element Method as for structural
analysis), flow simulations are a ubiquitous part of the design process. CAM systems are
used for simulation and optimization of manufacturing, and NC code is created and loaded to
NC machines.
Future[edit]
The past of CAD has been full of unmet expectations; this continues. Some anticipate 3D
modelling without flat screens or mouse pointers -- a fully immersive 3D environment where
modelling tools include special gloves and goggles. In the future, designing will be closer to
sculpting than painting.
Up to now, 3D goggles cause nausea, immersive technologies are expensive and complex,
and most designers prefer using a keyboard, stylus, and mouse.
While some of these optimistic predictions may come true, the more likely course is that the
future changes will evolve in ways we do not see now. Still, some trends seem more likely to
succeed and be widely adopted than others.
The following speculations are separated into strong probability of adoption, medium, and
weak.
CAD format standardization based on XML (strong)[edit]
CAD formats will follow development in Office applications, where XML based ODF (Open
Document Format) format is becomming standard. Similar standardization efforts for 3D and
CAD related formats are represented by X3D.
Companies and developers will start to implement X3D import/export as default way for data
exchange. This will enhance interoperability between CAD, and related applications like
CAE, CAM. 3D models created in CAD could be immediately presented in web browsers that
will be able to display 3D models (and to zoom, rotate ...).
=== Real time ray tracing Real time ray tracing is a resource intensive process. For example
one second of high resolution
In future there may be a strong open source CAD solution. It will probably be based the
Open CASCADE engine. Other probable scenario is that a CAD company will start an open
source project to boost its more profitable products based on same engine (for example
CAM or CAE).
There are many specialized tools that can speed up your design, minimize errors and
improve your results.
Terminology[edit]
Read about frequently used CAD/CAE/CAM terms on Wikipedia:
Follow the links to get acquainted with other terms and abbreviations used in the
CAD/CAE/CAM industry.
Design process[edit]
On the charts (gif and svg versions) you can see the generalized design, validation and
manufacturing process.
Each stage requires specific knowledge and skills, and often requires the use of specific
software.
Need or Idea[edit]
Usually the design process starts with a defined need. The need can be defined by market
research, by the requirements of a larger body of work (for example airplane part).
Sometimes, but more rarely than you may think, the design process is begun with a new idea
or invention.
At any rate, a needs analysis should precede any decision to undertake a project. This
includes defining the need in a highly detailed way, in writing. This is similar to the
requirements specification process in software engineering.
Research[edit]
Professionals tend to research available solutions before beginning their work. There is no
need to "reinvent the wheel".
You should study existing solutions and concepts, evaluating their weaknesses and
strengths. Your research should also cover available parts that you can use as a part of your
design. It is obvious, that Internet and search engines like Google are very helpful for this
task. There are also many libraries of standardized parts which you can import into your
project.
Concept[edit]
Based on your research, start with a high level concept. You should specify the main
principles and major parts. For example you can consider Diesel or Stirling engines for
stationary electric generators.
Draft[edit]
You can choose to create a draft by pen and paper. Some prefer to use simple vector
graphics programs, others even simple CAD (for example SmartSketch), yet others prefer to
start directly in their main CAD system.
Model Design[edit]
2D and 3D modeling in CAD. The designer creates a model with details, and this is the key
part of the design process, and often the most time consuming. This will be described in
greater detail in further lessons. asa ceva
Part Libraries[edit]
Standard parts, or parts created by other team members, can be used in your model (you
don't have to reinvent the wheel). Files representing a part can be downloaded from the
Internet, or local networks. They are also distributed on CD ROMs or together with CAD as
and extension (library). By putting these predefined parts into your project, you ensure that
they are correct and save a lot of time and effort. When working on a large project, this
becomes a requirement to ensure the parts operate together, swap out equivalent parts, and
coordinate distributed teams' work. This was, a standard part can be inserted into the project
by one team member, and used by all.hahaa
Assembly modeling[edit]
Parts are assembled into a machine or mechanism. Parts are put together using mating
conditions such as alignment of the axis of two holes. More about how to do this in further
lessons. cad is use in industries.
Analysis[edit]
Specialized programs (CAE -- Computer Aided Engineering) aid you in analysis of 3D model
robustness and performance. Many software tools are used for this task. Most notably FEM
(Finite Element Method) and Kinematics. Some CAD programs include these tools built in.
Engineering Drawings[edit]
From your 3D models, you generate a set of engineering drawings for manufacturing. These
drawings are then distributed to the departments and individuals responsible for producing
that work. Also these drawings must be toleranced for proper manufacturing.
Tool Design[edit]
You can use CAM software to simulate, optimize and prepare manufacturing. Generated NC
(Numeric Control) code is then executed by manufacturing machines like lathes or milling
cutters.
Planning[edit]
Critical Path Method, Gannt chart and other methods and tools are used by project
managers to plan and optimize manufacturing. Project management and ERP systems are
used.
Presentation[edit]
You should create photo realistic images and/or animations to present your design. This
allows you to get customer feedback even before the product is actually manufactured. You
can also consider using rapid prototyping techniques to present a physical 3D model.
Major CAD/CAE/CAM software companies develop and sell tools that cover the whole cycle.
These complex software tools support change management, teamwork, versioning and
resource planning.
Tasks to do[edit]
1. Play the role of an engineer who has to select an appropriate software package for
manufacturing.
2. Select a manufacturer of a specific consumer product. Choose a company that you
know, or find one on the Internet (preferably one with well-described products and
manufacturing processes).
3. Find at least two (2) appropriate CAD/CAE/CAM packages suitable for your selected
manufacturer. These software tools should support all the major design process
stages (modeling, analysis, tool design, and presentation). Tools for teamwork,
project management and planning is a plus.
4. Compare and contrast your selected tools in terms of functionality, their added value,
and price. (Use a weighted evaluation methodology to determine which included
CAD/CAM/CAE software functions are most valuable/appropriate to your chosen
manufacturer.)
Outcomes[edit]
Your focused research of CAD/CAE/CAM industry gives you an overview about available
tools and their producers. You have also become familiar with industry lingo and terminology.
After successfully accomplishing this task you will be able to initialize the CAD/CAE/CAM
software selection process for a specific industry.
Learning Assignment[edit]
Write a Paper (approxiamately 2 pages) with:
Computer-aided design/Objects
Introduction[edit]
A three dimensional (3D) computer model, for example a gear box, consists of many objects.
These objects are of several types, for example solid and surface types. We will look at 3D
model types and briefly discuss when to use them.
Workplane[edit]
Also called reference plane or coordinate-system. The workplane acts as a reference from
which the model data is calculated.
Point[edit]
A point represents a position in the 3D workspace and so is defined by x,y,z coordinates.
Points are usually used as reference to snap other objects onto.
Wireframe objects[edit]
Examples are lines, circles, arcs or curves in 2D or 3D space. Wireframe objects are defined
by control points and equation.
For example circle has center a,b (control point), radius r and equation defining set of all x,y
circle points.
Implicit function:
Parametric equation can be written using the trigonometric functions sine and cosine:
x = a + r cos(t)
y = b + r sin(t), where t is parametric variable.
Some wireframe objects like Beziér spline cannot be defined by control points
and simple function only. These objects are defined by many control points,
vectors in control vertices that define shape and set of x,y is is calculated by
algorithms (instead of simple equations).
Line
Arc
Circle (full arc)
Ellipse
Polyline - set of connected lines and arcs
Rectangle (special case of polygon)
Regular polygons
Polygon
Bézier curve (special case of B-spline)
B-spline (special case of NURBS)
NURBS - Nonuniform rational B-spline
Surfaces[edit]
You can understand surface as a part the the outer shape of an object or as an
idealized sheet metal with zero thickness. Surface can be represented in several
ways, but the most common is as a Parametric surface.
Types of surfaces:
Solid objects[edit]
A solid represents a complete physical body, usually part that can be
manufactured from one piece of material. Most CADs use method
called Boundary Representation (abbrev B-rep or BREP) , to represent solid in
computer. The object is represented by connected surfaces forming a closed
solid volume. Surface elements create boundary between solid and non-solid.
Solid objects have a volume and other physical and optical properties (mass,
density, opacity ...).
Sets of predefined solid primitives differ in various CADs. Commonly used are:
Box, Cuboid
Wedge
Cylinder
Cone
Sphere
Torus
Sweeping
Imagine that you want to model bent pipe. You can create it, by draw two
concentric circles that will form a doughnut shape. The doughnut shape is the
profile. Then you will draw and axis of the pipe. Axis can be straight line, arc or
any other curve. Then you will sweep the doughnut along the defining path (pipe
axis).
Extrusions or rotations are special cases of sweeping. You can create a solid
box from a 2D rectangle by extrusion along the Z axis, or you can draw a 2D
circle and rotate it 180 degrees to create sphere.
You can use boolean operations to create more complex solid objects.
Subtraction is similar to drilling. Draw a box and a cylinder inside it. By
subtracting the cylinder from the box you will get a box with a hole. Unions are
similar to welding in that it joins two solid bodies together.
Feature[edit]
Many modern CADs use features.
Features are for example a hole or slot applied to solid object. Often features
are used with parametric geometry constraints. For example a hole must be in
the center of the disk.
Solid modelling should be used for models that consist from relatively regular
shapes. Engines, gear boxes and machinery like lathe are typical examples.
Parts are usually put together by assembly modelling. Making changes is
usually fast, especially when features and parametric modelling is used.
Tasks to do[edit]
Learn about CAD math background. Learn more about parametric equations.
Achievements[edit]
You now have a basic understanding of CAD objects. You also have an idea of
how these objects are represented in a computer. You also know some math
behind the construction of these objects.
Deliveries[edit]
Parametric equations for some simple 3D surface (cylinder, sphere, ellipsoid).
Computer-aided design/Software
Introduction[edit]
We will discuss how a CAD software works. We will even create our own 2D CAD, ... well
sort of ...
Database[edit]
Typically CAD software is built upon some database stored in the hard disk. From the user's
point of view it is a file. CAD objects such as a line or circle, however, are stored as
structured records. The CAD engine has implemented methods for fast data retrieval and
storage.
Object model[edit]
Data is read from the hard disk into memory RAM as an object model. Each graphical
element is represented as an object. Changes are made by manipulating these objects in
RAM. And then stored in the database on permanent storage such as the hard disk.
Modeling kernel[edit]
The modeling kernel is a set of methods generally programmed in a low level programming
language such as C. Libraries contain methods for creating graphical objects (draw line,
extrude, etc.) as well manipulating them (rotate, join, union, etc.). These operations are
mainly based on parametric equations and due to the number of objects and vertexes are
often time consuming. Since these arithmetical operations are running in the
computer's CPU, computers used for CAD tend to have high end processors.
Visualization[edit]
Tasks to do[edit]
As good engineers, we will create a simple CAD from cheap and widely available
components. Quite probably you have them already installed.
We will use:
To:
Lesson[edit]
Step One - Draw Line[edit]
Let's start with something simple, very simple. We will draw SVG line from point 0,0 to
100,100. SVG is a standard defined by W3C Consortium. We will use W3C SVG 1.1
reference, especially line definition and examples. Write following code using any text editor
such as Notepad.
<?xml version="1.0"?>
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"
version="1.1">
<line x1="0" y1="0" x2="100" y2="100" stroke="black"/>
</svg>
... save it as a text file, for example linetest.svg. Open it in browser and ... you should see the
line.
Although XML is almost self explainable and you probably have got the idea, let's comment
the example a little.
First line <?xml version="1.0"?> defines that structure is XML, and you must follow
the rules like "every element has name, element must be enclosed in <>, element must
be closed, element can have attributes ..."
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" version="1.1">
means that SVG standard is used and graphics will be displayed in 200x200 square.
<line x1="0" y1="0" x2="100" y2="100" stroke="black"/> means "draw black line from
point 0,0 to point 100,100"
Play with SVG commands a little. For example cross the thin black line (you already have)
with thick blue line. To achieve this, just add one line to text file and reopen it in browser
(reload works, too). Use above mentioned SVG reference and examples.
Your text should look like this:
<?xml version="1.0"?>
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"
version="1.1">
<line x1="0" y1="0" x2="100" y2="100" stroke="black"/>
<line x1="0" y1="100" x2="100" y2="0" stroke="blue" stroke-
width="2"/>
</svg>
File:SVGCADLesson1.jpg
If you do not see lines as depicted above, check if your browser hads SVG support (in the
case of MS IE, you need to have a SVG plugin installed such as Adobe). Also check if your
text is valid XML-SVG document, for example all elements must be closed
(<XXX>...</XXX>), double check mistypings...
If everything works, let's extend our example a little and create something more fancy to get
acquainted with SVG capabilities. Just a few tips:
<?xml version="1.0"?>
<svg
id="svgarea"
onload="createRandomBlueLine()"
xmlns="http://www.w3.org/2000/svg"
width="200"
height="200"
>
<script type="text/ecmascript"><![CDATA[
var svgNS = "http://www.w3.org/2000/svg";
function createRandomBlueLine() {
var newUseEl =
document.createElementNS(svgNS,"line");
newUseEl.setAttributeNS(null,"x1",Math.random() * 200);
newUseEl.setAttributeNS(null,"y1",Math.random() * 200);
newUseEl.setAttributeNS(null,"x2",Math.random() * 200);
newUseEl.setAttributeNS(null,"y2",Math.random() * 200);
newUseEl.setAttributeNS(null,"stroke-
width","1");
newUseEl.setAttributeNS(null,"stroke","blue");
document.getElementById("svgarea").appendChild(newUseEl);
}
]]></script>
</svg>
... again save this code as text file, and open it in your browser. You should see the blue line.
After refresh or reopening you should observe lines in random directions and lengths.
Let's look at the code again. There is svg root element similar as in previous static example.
But it has additional attribute onload="createRandomBlueLine()", meaning "Immediately after
text file content is loaded call function that will create blue line with random length and
direction". There is also another new attributeid="svgarea". This attribute is an identifier
which is used to locate the correct element in the tree. In our simple example, where we
have only one element it has no obvious meaning, but the tree can be quite large and
searching can be quite long. Worse than that, there can be more elements with the same tag
(name) and the program might not easily decide with which element it should work. The ID
must be unique in the scope of XML document and so the ID fully identifies one element. We
will use this identifier later to address svg element in JavaScript function.
JavaScript function createRandomBlueLine(). When browser reads XML from file, it also
creates objects and places them into tree structure. This process takes place in computer
memory. Objects and tree structure is called DOM. Root DOM object is called document.
That is why var newUseEl = document.createElementNS(svgNS,"line"); will create new
element with tag line as a part of document object. Now we can enhance our new
element line. CommandnewUseEl.setAttributeNS(null,"x1",Math.random() * 200); creates
attribute x1 with calculated random value. Similar result you can get by writing <line
x1="123"/> in XML document. Next few lines in JavaScript function just adds few more
attributes with random or fixed values. Last
commanddocument.getElementById("svgarea").appendChild(newUseEl); finds element by
its identifier (in our case it is element <svg id="svgarea" ...>) and places newly created
element (line) to correct place in the tree (as a child of svg element).
If you will think about this small example a little more, you could see, that XML is parsed from
text to memory representation called DOM and you can see the way, how to manipulate it
using programming language. Try to add an error for example add unclosed element for
example one line with <x>. You should see error message after trying to display it in the
browser. What happened? Browser tried to create DOM, but failed due to syntax errors.
Further execution was stopped, while without valid DOM all other tasks does not make
sense.
If everything works, we can enhance our example to RSCAD (Really Simple CAD). We will
add functionality, that will enable user interactions.
newUseEl.setAttributeNS(null,"x1",Math.random() * 500);
newUseEl.setAttributeNS(null,"y1",Math.random() * 500);
newUseEl.setAttributeNS(null,"x2",Math.random() * 500);
newUseEl.setAttributeNS(null,"y2",Math.random() * 500);
newUseEl.setAttributeNS(null,"stroke-
width","1");
newUseEl.setAttributeNS(null,"stroke","blue");
document.getElementById("drawGroup").appendChild(newUseEl);
}
function createLine() {
var newUseEl =
document.createElementNS(svgNS,"line");
var x1 = prompt('1st point X','10');
var y1 = prompt('1st point Y','10');
var x2 = prompt('2nd point X','100');
var y2 = prompt('2nd point Y','100');
var color = prompt('Stroke color','black');
newUseEl.setAttributeNS(null,"x1",x1);
newUseEl.setAttributeNS(null,"y1",y1);
newUseEl.setAttributeNS(null,"x2",x2);
newUseEl.setAttributeNS(null,"y2",y2);
newUseEl.setAttributeNS(null,"stroke-
width","1");
newUseEl.setAttributeNS(null,"stroke",color);
document.getElementById("drawGroup").appendChild(newUseEl);
}
]]></script>
<g id="menuGroup">
<text x="10" y="30" font-size="12px">Click to
draw:</text>
<text x="25" y="45" onclick="createRandomBlueLine()"
font-size="14px">- random line</text>
<text x="25" y="60" onclick="createLine()" font-
size="14px">- line</text>
</g>
<g id="drawGroup" transform="translate(150,10)">
<rect x="0" y="0" width="650" height="590" fill="none"
stroke="black" stroke-width="1"/>
<text x="0" y="0" font-size="10px">0,0</text>
<text x="500" y="0" font-size="10px">500,0</text>
<text x="0" y="500" font-size="10px">0,500</text>
</g>
</svg>
Copy this code to file, for example rscad.svg and open it in the browser.
Explanations and hints: We added new SVG element <g id="menuGroup">. This is group
element that groups several elements together. Attributetransform="translate(150,10)" then
transforms all X,Y coordinates in the group. SVG text element <text x="25" y="60"
onclick="createLine()"> display text and calls JavaScript function createLine() when user
clicks on the displayed text. JavaScript command var x1 = prompt('1st point X','10'); then
displays edit box and stores value to variable. Variable is then used to set attribute values
of line SVG element.
Now we have really simple CAD. You can even use it for some real tasks. However you will
probably use server-side technology like PHP and Apache, you will probably create menu
not as SVG text, but HTML menus instead, but in general, principle will remain the same.
Tasks to do[edit]
Study the example and play with it. Then try to enhance it. Add functions and menu entries
for:
If you will have something valuable, do not hesitate to place it here, so that others can be
inspired by your example.
Achievements[edit]
You have a basic understanding of how CAD software is made and how it works. More than
that, you can even create your own simple 2D CAD and show it on Internet.
Deliveries[edit]
Simple 2D CAD model based on SVG and ECMA script.