How to draw a 3D sphere in HTML5?

To create a 3D sphere in HTML5, you need to use the canvas element along with mathematical calculations to plot points in 3D space and project them onto a 2D canvas. This involves creating vertices using spherical coordinates and rendering them as a wireframe or solid sphere.

Basic Sphere Class Structure

First, let's create a Point3D class and a sphere display function:

<!DOCTYPE html>
<html>
<head>
    <title>3D Sphere</title>
</head>
<body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
        // Point3D class to represent 3D coordinates
        function Point3D(x, y, z) {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
        }

        // Sphere class
        function Sphere(radius) {
            this.points = [];
            this.radius = (typeof(radius) === "undefined") ? 50 : radius;
            this.radius = (typeof(radius) !== "number") ? 50 : radius;
            this.vertexCount = 0;
            
            this.generateVertices();
        }

        Sphere.prototype.generateVertices = function() {
            // Generate sphere vertices using spherical coordinates
            for (let phi = 0; phi <= Math.PI; phi += 0.2) {
                for (let theta = 0; theta <= 2 * Math.PI; theta += 0.2) {
                    let x = this.radius * Math.sin(phi) * Math.cos(theta);
                    let y = this.radius * Math.cos(phi);
                    let z = this.radius * Math.sin(phi) * Math.sin(theta);
                    
                    this.points.push(new Point3D(x, y, z));
                    this.vertexCount++;
                }
            }
        };

        // Simple 3D to 2D projection
        function project(point, canvas) {
            let distance = 200;
            let scale = distance / (distance + point.z);
            
            return {
                x: canvas.width/2 + point.x * scale,
                y: canvas.height/2 + point.y * scale
            };
        }

        // Draw the sphere
        function drawSphere() {
            let canvas = document.getElementById('canvas');
            let ctx = canvas.getContext('2d');
            
            // Clear canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // Create sphere
            let sphere = new Sphere(80);
            
            ctx.fillStyle = 'blue';
            ctx.strokeStyle = 'darkblue';
            
            // Draw each point
            sphere.points.forEach(function(point) {
                let projected = project(point, canvas);
                
                ctx.beginPath();
                ctx.arc(projected.x, projected.y, 2, 0, 2 * Math.PI);
                ctx.fill();
            });
        }

        // Draw when page loads
        drawSphere();
    </script>
</body>
</html>

Creating a Wireframe Sphere

For a more structured wireframe appearance, you can connect the vertices with lines:

<!DOCTYPE html>
<html>
<head>
    <title>Wireframe Sphere</title>
</head>
<body>
    <canvas id="wireframe" width="400" height="400"></canvas>
    <script>
        function WireframeSphere(radius) {
            this.radius = radius || 60;
            this.rings = [];
            this.generateRings();
        }

        WireframeSphere.prototype.generateRings = function() {
            let ringCount = 10;
            let pointsPerRing = 20;
            
            for (let i = 0; i <= ringCount; i++) {
                let ring = [];
                let phi = (i / ringCount) * Math.PI;
                let ringRadius = Math.sin(phi) * this.radius;
                let y = Math.cos(phi) * this.radius;
                
                for (let j = 0; j < pointsPerRing; j++) {
                    let theta = (j / pointsPerRing) * 2 * Math.PI;
                    let x = ringRadius * Math.cos(theta);
                    let z = ringRadius * Math.sin(theta);
                    
                    ring.push(new Point3D(x, y, z));
                }
                this.rings.push(ring);
            }
        };

        function drawWireframeSphere() {
            let canvas = document.getElementById('wireframe');
            let ctx = canvas.getContext('2d');
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.strokeStyle = 'blue';
            ctx.lineWidth = 1;
            
            let sphere = new WireframeSphere(80);
            
            // Draw horizontal rings
            sphere.rings.forEach(function(ring) {
                ctx.beginPath();
                ring.forEach(function(point, index) {
                    let projected = project(point, canvas);
                    
                    if (index === 0) {
                        ctx.moveTo(projected.x, projected.y);
                    } else {
                        ctx.lineTo(projected.x, projected.y);
                    }
                });
                ctx.closePath();
                ctx.stroke();
            });
            
            // Draw vertical lines
            for (let i = 0; i < 20; i += 2) {
                ctx.beginPath();
                sphere.rings.forEach(function(ring, ringIndex) {
                    if (ring[i]) {
                        let projected = project(ring[i], canvas);
                        if (ringIndex === 0) {
                            ctx.moveTo(projected.x, projected.y);
                        } else {
                            ctx.lineTo(projected.x, projected.y);
                        }
                    }
                });
                ctx.stroke();
            }
        }

        function Point3D(x, y, z) {
            this.x = x || 0;
            this.y = y || 0; 
            this.z = z || 0;
        }

        function project(point, canvas) {
            let distance = 200;
            let scale = distance / (distance + point.z);
            
            return {
                x: canvas.width/2 + point.x * scale,
                y: canvas.height/2 + point.y * scale
            };
        }

        drawWireframeSphere();
    </script>
</body>
</html>

Key Components Explained

Spherical Coordinates: Use phi (latitude) and theta (longitude) angles to generate points on the sphere surface using the formulas:

  • x = radius × sin(phi) × cos(theta)
  • y = radius × cos(phi)
  • z = radius × sin(phi) × sin(theta)

3D Projection: Convert 3D coordinates to 2D screen coordinates using perspective projection with a simple distance-based scaling formula.

Comparison of Approaches

Method Appearance Performance Complexity
Point Cloud Dotted sphere Fast Simple
Wireframe Grid lines Medium Moderate
Solid Surface Filled triangles Slow Complex

Conclusion

Creating a 3D sphere in HTML5 involves generating vertices using spherical coordinates and projecting them onto the 2D canvas. Start with a simple point-based approach and gradually add complexity for wireframes or solid surfaces as needed.

Updated on: 2026-03-15T23:18:59+05:30

868 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements