Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วาดทรงกลม 3D (Sphere) ใน HTML5 Canvas

ใช้ Canvas 2D Context วาด Wireframe Sphere (Pseudo-3D)

คำนวณจุดบนพื้นผิวทรงกลม (Latitude/Longitude) แล้ว Project มา 2D

Constructor Function

function Sphere(r) {
    this.point = [];
    this.color = "blue";
    this.r = (typeof r === "number") ? r : 20.0;
    this.vertexes = 0;
    
    for (var alpha = 0; alpha <= 6.28; alpha += 0.17) { // Longitude
        var p = this.point[this.vertexes] = { x: 0, y: 0, z: 0 };
        p.x = Math.cos(alpha) * this.r;
        p.y = 0;
        p.z = Math.sin(alpha) * this.r;
        this.vertexes++;
    }
    // ต้องเพิ่ม Latitude loops และ Projection Logic เพื่อวาดจริง
}

หมายเหตุ: โค้ดนี้สร้างจุดรอบ Equator เท่านั้น การวาด Sphere 3D จริงบน Canvas 2D ต้องใช้ Projection (Orthographic/Perspective) และ Depth Sorting แนะนำใช้ Three.js (WebGL) แทนจะง่ายและเร็วกว่ามาก