Govt. P.G.
Nehru College, Jhajjar
(Haryana)
Subject: Computer graphics
Submitted By: Name:
Course: Master of Science (Computer Science)
Roll No.: 22417250
Submitted To: Name:
Academic Session: 2025-2026
Index
1. Create a program to draw concentric circles and lines radiating from a center point,
forming a basic radial pattern.
2. Implement the DDA line drawing algorithm. Allow the user to input start and end
points for the line and compare the outputs.
3. Implement the Bresenham’s line drawing algorithm. Allow the user to input start
and end points for the Line and compare the outputs.
4. Implement the Mid-point circle drawing algorithm. Allow the user to input center
and radius for the circle.
5. Write a program to implement the scanline polygon filling algorithm. Use it to fill a
closed polygon with a solid color.
6. Draw a speaker icon with volume ON/OFF that is drawn on a toggle of a button.
7. Implement the seed fill method with/without recursion.
8. Implement scan-line fill algorithm.
[Link] some screensaver animation based on circles.
10. Develop a program to implement the Cohen-Sutherland line clipping algorithm.
Allow the user to input A rectangular clipping window and several lines for clipping.
11. Use Blender to model a simple chair. Create meshes, apply materials, and render
the final output.
Teacher sign -……….
PROGRAM
Create a program to draw concentric circles and lines radiating from a
center point, forming a basic radial pattern.
C Program (graphics.h)
#include <graphics.h>
#include <conio.h>
#include <math.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Adjust path if needed
int cx = 300; // Center x-coordinate
int cy = 300; // Center y-coordinate
int radiusStep = 30; // Distance between circles
int numCircles = 5; // Number of concentric circles
int numLines = 36; // Number of radiating lines
// Draw concentric circles
for (int i = 1; i <= numCircles; i++) {
circle(cx, cy, i * radiusStep);
}
// Draw radiating lines
for (int i = 0; i < numLines; i++) {
float angle = (2 * 3.14159265 / numLines) * i; // angle in radians
int x = cx + (numCircles * radiusStep) * cos(angle);
int y = cy + (numCircles * radiusStep) * sin(angle);
line(cx, cy, x, y);
}
getch();
closegraph();
return 0;
}
OUTPUT:
Visually, it looks like this (schematic):
* *
* O O *
* O O *
* O O *
* O *
|
|
Center
O represents circles.
* represents the ends of lines radiating from the center.
PROGRAM
Implement the DDA line drawing algorithm. Allow the user to input start and end points for
the line and compare the outputs.
C Program: DDA Line Drawing Algorithm
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
// Function to implement DDA line drawing algorithm
void drawLineDDA(int x0, int y0, int x1, int y1, int color) {
int dx = x1 - x0;
int dy = y1 - y0;
int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
float xInc = dx / (float)steps;
float yInc = dy / (float)steps;
float x = x0;
float y = y0;
for (int i = 0; i <= steps; i++) {
putpixel(round(x), round(y), color);
x += xInc;
y += yInc;
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Adjust path if needed
int x0, y0, x1, y1;
// Input start and end points
printf("Enter x0 y0: ");
scanf("%d %d", &x0, &y0);
printf("Enter x1 y1: ");
scanf("%d %d", &x1, &y1);
// Draw line using DDA algorithm in RED
drawLineDDA(x0, y0, x1, y1, RED);
// Draw line using built-in line() in BLUE for comparison
line(x0, y0, x1, y1);
getch();
closegraph();
return 0;
}
OUTPUT:
If the user enters:
x0 = 100, y0 = 100
x1 = 400, y1 = 300
Red line → drawn using DDA algorithm
Blue line → drawn using built-in line() function
PROGRAM
Implement the Bresenham's line drawing algorithm. Allow the user to input start and end
points for the line and compare the outputs.
C Program: Bresenham’s Line Drawing Algorithm
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
// Function to draw line using Bresenham's algorithm
void drawLineBresenham(int x0, int y0, int x1, int y1, int color) {
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1; // Step direction in x
int sy = y0 < y1 ? 1 : -1; // Step direction in y
int err = dx - dy;
while (1) {
putpixel(x0, y0, color);
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Adjust path if needed
int x0, y0, x1, y1;
// Input start and end points
printf("Enter x0 y0: ");
scanf("%d %d", &x0, &y0);
printf("Enter x1 y1: ");
scanf("%d %d", &x1, &y1);
// Draw line using Bresenham's algorithm in RED
drawLineBresenham(x0, y0, x1, y1, RED);
// Draw line using built-in line() in BLUE for comparison
line(x0, y0, x1, y1);
getch();
closegraph();
return 0;
}
OUTPUT:
User input:
x0 = 100, y0 = 100
x1 = 400, y1 = 300
Red pixels → Bresenham line
Blue line → built-in function
PROGRAM
Implement the Mid-point circle drawing algorithm. Allow the user to input center and
radius for the circle.
C Program: Midpoint Circle Algorithm
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
// Function to plot all eight symmetric points of a circle
void plotCirclePoints(int xc, int yc, int x, int y, int color) {
putpixel(xc + x, yc + y, color);
putpixel(xc - x, yc + y, color);
putpixel(xc + x, yc - y, color);
putpixel(xc - x, yc - y, color);
putpixel(xc + y, yc + x, color);
putpixel(xc - y, yc + x, color);
putpixel(xc + y, yc - x, color);
putpixel(xc - y, yc - x, color);
}
// Midpoint Circle Drawing Algorithm
void drawCircleMidpoint(int xc, int yc, int r, int color) {
int x = 0;
int y = r;
int p = 1 - r;
plotCirclePoints(xc, yc, x, y, color);
while (x < y) {
x++;
if (p < 0) {
p += 2 * x + 1;
} else {
y--;
p += 2 * (x - y) + 1;
}
plotCirclePoints(xc, yc, x, y, color);
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Adjust path if needed
int xc, yc, r;
// Input center and radius
printf("Enter center coordinates (xc yc): ");
scanf("%d %d", &xc, &yc);
printf("Enter radius: ");
scanf("%d", &r);
// Draw circle using Midpoint Circle Algorithm in RED
drawCircleMidpoint(xc, yc, r, RED);
getch();
closegraph();
return 0;
}
Output Example
User input:
Center: xc = 300, yc = 300
Radius: r = 100
The program draws a red circle centered at (300, 300) with radius 100.
Pixels are plotted symmetrically for a smooth circle.
PROGRAM
Write a program to implement the scanline polygon filling algorithm. Use it to fill a closed
polygon with a solid color
C Program: Scanline Polygon Filling
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
#define MAX 20 // Maximum number of vertices
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Adjust path if needed
int n; // Number of vertices
int x[MAX], y[MAX];
printf("Enter number of vertices of polygon (3-20): ");
scanf("%d", &n);
if (n < 3 || n > MAX) {
printf("Invalid number of vertices!\n");
return 0;
}
printf("Enter the vertices (x y) in order:\n");
for (int i = 0; i < n; i++) {
scanf("%d %d", &x[i], &y[i]);
}
// Draw polygon edges
for (int i = 0; i < n; i++) {
line(x[i], y[i], x[(i+1)%n], y[(i+1)%n]);
}
// Find min and max y to limit scanlines
int yMin = y[0], yMax = y[0];
for (int i = 1; i < n; i++) {
if (y[i] < yMin) yMin = y[i];
if (y[i] > yMax) yMax = y[i];
}
// Scanline filling
for (int scanY = yMin; scanY <= yMax; scanY++) {
int intersections[MAX], count = 0;
// Find intersections with polygon edges
for (int i = 0; i < n; i++) {
int x1 = x[i], y1 = y[i];
int x2 = x[(i+1)%n], y2 = y[(i+1)%n];
if (y1 == y2) continue; // Ignore horizontal edges
if (scanY < ((y1 < y2) ? y1 : y2) || scanY > ((y1 > y2) ? y1 :
y2))
continue;
// Compute intersection x-coordinate
int interX = x1 + (float)(scanY - y1) * (x2 - x1) / (y2 - y1);
intersections[count++] = interX;
}
// Sort intersections (simple bubble sort)
for (int i = 0; i < count-1; i++) {
for (int j = 0; j < count-i-1; j++) {
if (intersections[j] > intersections[j+1]) {
int temp = intersections[j];
intersections[j] = intersections[j+1];
intersections[j+1] = temp;
}
}
}
// Draw pixels between pairs of intersections
for (int i = 0; i < count; i += 2) {
if (i+1 < count)
for (int xFill = intersections[i]; xFill <=
intersections[i+1]; xFill++)
putpixel(xFill, scanY, RED);
}
}
getch();
closegraph();
return 0;
}
Example Input
Number of vertices: 4
Vertices:
100 100
200 100
200 200
100 200
This draws a square and fills it with red color.
✅Output
A polygon is drawn and filled solidly with the chosen color (RED in this example).
PROGRRAM
Draw a speaker icon with volume ON/OFF that is drawn on a toggle of a button.
SVG Toggle Button With Speaker ON/OFF Icons
Preview behavior
Left (toggle OFF) → Speaker muted (slash through icon)
Right (toggle ON) → Speaker with sound waves
HTML + SVG + CSS Toggle
<style>
.toggle {
width: 80px;
height: 40px;
background: #ccc;
border-radius: 40px;
position: relative;
cursor: pointer;
}
.toggle input {
display: none;
}
.knob {
width: 36px;
height: 36px;
background: white;
border-radius: 50%;
position: absolute;
top: 2px;
left: 2px;
transition: 0.28s ease;
}
.toggle input:checked + .knob {
transform: translateX(40px);
}
.icon {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 22px;
height: 22px;
fill: black;
}
.[Link] {
left: 8px;
}
.[Link] {
right: 8px;
}
</style>
<label class="toggle">
<input type="checkbox" id="vol-toggle">
<div class="knob"></div>
<!-- Volume OFF Icon -->
<svg class="icon off" viewBox="0 0 24 24">
<path d="M3 9v6h4l5 5V4L7 9H3z"/>
<line x1="16" y1="8" x2="22" y2="14"
stroke="black" stroke-width="2"/>
<line x1="22" y1="8" x2="16" y2="14"
stroke="black" stroke-width="2"/>
</svg>
<!-- Volume ON Icon -->
<svg class="icon on" viewBox="0 0 24 24">
<path d="M3 9v6h4l5 5V4L7 9H3z"/>
<path d="M16 8c1.5 1.5 1.5 4.5 0 6
M18.5 5.5c3 3 3 9 0 12"
stroke="black" stroke-width="2"
fill="none"/>
</svg>
</label>
OUTPUT:
<svg width="200" height="80" viewBox="0 0 200 80"
xmlns="[Link]
<!-- Toggle background -->
<rect x="10" y="20" width="180" height="40" rx="20"
fill="#ccc"/>
<!-- OFF label speaker icon -->
<g transform="translate(30, 40) scale(1.2)">
<path d="M0 -6v12h8l10 10V-16L8 -6H0z" fill="black"/>
<line x1="22" y1="-10" x2="32" y2="0" stroke="black"
stroke-width="2"/>
<line x1="32" y1="-10" x2="22" y2="0" stroke="black"
stroke-width="2"/>
</g>
<!-- ON label speaker icon -->
<g transform="translate(150, 40) scale(1.2)">
<path d="M0 -6v12h8l10 10V-16L8 -6H0z" fill="black"/>
<path d="M22 -8c3 3 3 9 0 12" stroke="black" stroke-
width="2" fill="none"/>
<path d="M26 -11c5 5 5 17 0 22" stroke="black" stroke-
width="2" fill="none"/>
</g>
<!-- Slider knob (centered) -->
<circle cx="100" cy="40" r="18" fill="white" stroke="#888"
stroke-width="2"/>
PROGRAM
Implement the seed fill method with/without recursion.
1. Recursive Seed Fill (4-way fill)
Python Implementation
def seed_fill_recursive(x, y, target_color, replacement_color, img):
# Bounds check
if x < 0 or x >= len(img[0]) or y < 0 or y >= len(img):
return
# Stop if color does not match target
if img[y][x] != target_color or img[y][x] == replacement_color:
return
# Fill current pixel
img[y][x] = replacement_color
# Recursively fill neighbors (4-way)
seed_fill_recursive(x+1, y, target_color, replacement_color, img)
seed_fill_recursive(x-1, y, target_color, replacement_color, img)
seed_fill_recursive(x, y+1, target_color, replacement_color, img)
seed_fill_recursive(x, y-1, target_color, replacement_color, img)
✅2. Non-Recursive Seed Fill (Iterative, using Stack)
This is the safe version for large areas.
Python Implementation
def seed_fill_iterative(x, y, target_color, replacement_color, img):
if target_color == replacement_color:
return
stack = [(x, y)]
while stack:
cx, cy = [Link]()
# Bounds check
if cx < 0 or cx >= len(img[0]) or cy < 0 or cy >= len(img):
continue
# Skip pixels not matching target
if img[cy][cx] != target_color:
continue
# Fill pixel
img[cy][cx] = replacement_color
# Push neighbors (4-way)
[Link]((cx+1, cy))
[Link]((cx-1, cy))
[Link]((cx, cy+1))
[Link]((cx, cy-1))
Output:
['X', 'X', 'X', 'B']
['X', 'B', 'X', 'B']
['X', 'X', 'X', 'B']
PROGRAM
Implement scan-line fill algorithm.
1. How Scan-Line Seed Fill Works
Unlike recursive flood fill, scan-line fill:
Fills one entire horizontal run at a time
Pushes only the necessary segments into the stack
Avoids revisiting pixels
Never overflows the recursion stack
Algorithm Steps
1. Start at seed pixel (x, y).
2. Move left and right filling until hitting non-target pixels.
3. Record the filled segment range [x_left, x_right].
4. Look at the lines above and below this segment.
5. For each line, scan only within the horizontal bounds and push new seed points where
needed.
6. Repeat until stack is empty.
This is far faster than recursive flood fill.
✅2. Python Implementation (Scan-Line Flood Fill)
def scanline_fill(x, y, target_color, replacement_color, img):
height = len(img)
width = len(img[0])
if target_color == replacement_color:
return
stack = [(x, y)]
while stack:
x, y = [Link]()
# Skip if color is not target
if img[y][x] != target_color:
continue
# 1. Move left
left = x
while left >= 0 and img[y][left] == target_color:
left -= 1
left += 1
# 2. Move right
right = x
while right < width and img[y][right] == target_color:
right += 1
right -= 1
# 3. Fill the entire horizontal segment
for i in range(left, right + 1):
img[y][i] = replacement_color
# 4. Check the above and below scanlines
for nx in range(left, right + 1):
# Above
if y > 0 and img[y - 1][nx] == target_color:
[Link]((nx, y - 1))
# Below
if y < height - 1 and img[y + 1][nx] == target_color:
[Link]((nx, y + 1))
Output:
['X', 'X', 'X', 'X', 'B']
['X', 'B', 'X', 'X', 'B']
['X', 'X', 'X', 'B', 'B']
['B', 'B', 'X', 'X', 'X']
PROGRAM
Draw some screensaver animation based on circles.
Circle Screensaver Animation (HTML + Canvas + JavaScript)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Circle Screensaver</title>
<style>
html, body {
margin: 0;
padding: 0;
overflow: hidden;
background: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="screen"></canvas>
<script>
const canvas = [Link]("screen");
const ctx = [Link]("2d");
function resize() {
[Link] = [Link];
[Link] = [Link];
}
[Link] = resize;
resize();
class Circle {
constructor() {
[Link]();
}
reset() {
this.x = [Link]() * [Link];
this.y = [Link]() * [Link];
this.r = 10 + [Link]() * 40;
[Link] = ([Link]() - 0.5) * 2;
[Link] = ([Link]() - 0.5) * 2;
[Link] = `hsla(${[Link]() * 360}, 80%, 60%, 0.7)`;
}
update() {
this.x += [Link];
this.y += [Link];
if (this.x < this.r || this.x > [Link] - this.r) [Link] *= -1;
if (this.y < this.r || this.y > [Link] - this.r) [Link] *= -
1;
}
draw() {
[Link]();
[Link] = [Link];
[Link] = 15;
[Link] = [Link];
[Link](this.x, this.y, this.r, 0, [Link] * 2);
[Link]();
[Link] = 0;
}
}
const circles = [];
for (let i = 0; i < 50; i++) [Link](new Circle());
function animate() {
[Link](0, 0, [Link], [Link]);
for (const c of circles) {
[Link]();
[Link]();
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
OUTPUT:
Circle Screensaver Animation (HTML + Canvas + JavaScript)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Circle Screensaver</title>
<style>
html, body {
margin: 0;
padding: 0;
overflow: hidden;
background: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="screen"></canvas>
PROGRAM
Use Blender to model a simple chair. Create meshes, apply materials, and
render the final output.
Blender Python Script — Simple Chair Model + Materials +
Render
import bpy
import math
# -------------------------------
# Cleanup default scene
# -------------------------------
[Link].select_all(action='SELECT')
[Link](use_global=False)
# -------------------------------
# Create Seat
# -------------------------------
[Link].primitive_cube_add(size=2, location=(0, 0, 1))
seat = [Link]
[Link][2] = 0.2 # Make it flat
# Material for seat
seat_mat = [Link]("SeatMat")
seat_mat.diffuse_color = (0.8, 0.5, 0.2, 1)
[Link](seat_mat)
# -------------------------------
# Create Backrest
# -------------------------------
[Link].primitive_cube_add(size=2, location=(0, -0.9, 2))
backrest = [Link]
[Link] = (1, 0.2, 1)
back_mat = [Link]("BackrestMat")
back_mat.diffuse_color = (0.7, 0.4, 0.2, 1)
[Link](back_mat)
# -------------------------------
# Create 4 Legs
# -------------------------------
leg_mat = [Link]("LegMat")
leg_mat.diffuse_color = (0.2, 0.2, 0.2, 1)
LEG_POSITIONS = [
(0.8, 0.8, 0.6),
(-0.8, 0.8, 0.6),
(0.8, -0.8, 0.6),
(-0.8, -0.8, 0.6),
]
for pos in LEG_POSITIONS:
[Link].primitive_cube_add(size=0.3, location=pos)
leg = [Link]
[Link][2] = 2.5
[Link](leg_mat)
# -------------------------------
# Lighting
# -------------------------------
[Link].light_add(type='AREA', location=(5, 5, 6))
light = [Link]
[Link] = 500
# -------------------------------
# Camera Setup
# -------------------------------
[Link].camera_add(location=(6, -6, 4), rotation=([Link](70), 0,
[Link](45)))
camera = [Link]
[Link] = camera
# -------------------------------
# Rendering Settings
# -------------------------------
scene = [Link]
[Link] = 'CYCLES'
[Link] = 64
[Link].image_settings.file_format = 'PNG'
[Link] = "//chair_render.png"
# -------------------------------
# Render Image
# -------------------------------
[Link](write_still=True)
print("Render saved as chair_render.png")
OUTPUT:
1. A visual schematic of the chair model (text-based)
This shows the structure that the Blender script creates:
┌─────────────── Backrest (Cube, thin)
│
│ [Backrest]
│ scale: (1, 0.2, 1)
│ position: (0, -0.9, 2)
│
┌──────────────────────────────┐
│ Seat │
│ (Cube flattened) │
└──────────────────────────────┘
│ │
Leg A Leg B
(Cube stretched) (Cube stretched)
│ │
Leg C Leg D
(Cube stretched) (Cube stretched)
Camera → Positioned diagonally
Light → Area light above scene
PROGRAM
Develop a program to implement the Cohen-Sutherland line clipping algorithm.
Allow the user to input a rectangular clipping window and several lines for
clipping.
Cohen–Sutherland Line Clipping — Full Program (Python)
# Cohen–Sutherland Line Clipping Algorithm
INSIDE = 0 # 0000
LEFT = 1 # 0001
RIGHT = 2 # 0010
BOTTOM = 4 # 0100
TOP = 8 # 1000
def compute_code(x, y, xmin, ymin, xmax, ymax):
code = INSIDE
if x < xmin: code |= LEFT
elif x > xmax: code |= RIGHT
if y < ymin: code |= BOTTOM
elif y > ymax: code |= TOP
return code
def cohen_sutherland_clip(x1, y1, x2, y2, xmin, ymin, xmax, ymax):
code1 = compute_code(x1, y1, xmin, ymin, xmax, ymax)
code2 = compute_code(x2, y2, xmin, ymin, xmax, ymax)
accept = False
while True:
# Case 1: both endpoints inside
if code1 == 0 and code2 == 0:
accept = True
break
# Case 2: both endpoints share an outside zone → reject
if code1 & code2 != 0:
break
# Pick one endpoint outside the window
if code1 != 0:
code_out = code1
else:
code_out = code2
# Intersection point
if code_out & TOP:
x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1)
y = ymax
elif code_out & BOTTOM:
x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1)
y = ymin
elif code_out & RIGHT:
y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1)
x = xmax
elif code_out & LEFT:
y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1)
x = xmin
# Replace outside point with intersection
if code_out == code1:
x1, y1 = x, y
code1 = compute_code(x1, y1, xmin, ymin, xmax, ymax)
else:
x2, y2 = x, y
code2 = compute_code(x2, y2, xmin, ymin, xmax, ymax)
if accept:
return True, (x1, y1, x2, y2)
else:
return False, None
# -----------------------------
# User Interface
# -----------------------------
if __name__ == "__main__":
print("\n=== Cohen–Sutherland Line Clipping ===\n")
xmin = float(input("Enter xmin: "))
ymin = float(input("Enter ymin: "))
xmax = float(input("Enter xmax: "))
ymax = float(input("Enter ymax: "))
n = int(input("\nHow many lines? "))
lines = []
for i in range(n):
print(f"\nLine {i+1}:")
x1 = float(input(" x1 = "))
y1 = float(input(" y1 = "))
x2 = float(input(" x2 = "))
y2 = float(input(" y2 = "))
[Link]((x1, y1, x2, y2))
print("\n--- Results ---\n")
for i, (x1, y1, x2, y2) in enumerate(lines, start=1):
accepted, clipped = cohen_sutherland_clip(x1, y1, x2, y2, xmin, ymin,
xmax, ymax)
if accepted:
cx1, cy1, cx2, cy2 = clipped
print(f"Line {i} ACCEPTED -> clipped: ({cx1:.2f}, {cy1:.2f}) to
({cx2:.2f}, {cy2:.2f})")
else:
print(f"Line {i} REJECTED")
OUTPUT:
Enter xmin: 0
Enter ymin: 0
Enter xmax: 10
Enter ymax: 8
How many lines? 2
Line 1:
x1 = -2
y1 = 4
x2 = 12
y2 = 4
Line 2:
x1 = -2
y1 = -2
x2 = -1
y2 = -5
--- Results ---
Line 1 ACCEPTED -> clipped: (0.00, 4.00) to (10.00, 4.00)
Line 2 REJECTED