DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How To Create a Resource Chart in JavaScript
  • Exploring Shadow DOM With Examples Using Cypress
  • Demystifying the ‘Class’ Attribute in HTML: A Comprehensive Guide With Examples
  • Cracking the Code: 7 Secrets Every Web Developer Should Know

Trending

  • Log Analysis Using grep
  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • Message Construction: Enhancing Enterprise Integration Patterns
  • How TIBCO Is Evolving Its Platform To Embrace Developers and Simplify Cloud Integration
  1. DZone
  2. Coding
  3. Languages
  4. HTML5 Canvas 3D Sphere

HTML5 Canvas 3D Sphere

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
Apr. 18, 12 · Interview
Like (0)
Save
Tweet
Share
10.99K Views

Join the DZone community and get the full member experience.

Join For Free
our new tutorial tells us how to create an animated 3d sphere (through direct access to pixels on the canvas). the sphere itself moves around the canvas continuously. this example should work in  most modern browsers (like firefox, chrome, safari and even in ie).

in the end, you should to get something like this:

html5 canvas 3d sphere

here are our demo and downloadable package:

live demo

download in package


ok, download the source files and let's start coding !


step 1. html

this is the markup of our page.

index.html

<div class="container">
    <canvas id="slideshow" width="1024" height="631"></canvas>
    <canvas id="obj" width="256" height="256"></canvas>
</div>

i prepared 2 canvas objects here: the first for the source image, and the second one for our sphere.

step 2. css

css/main.css

.container {
    height: 631px;
    margin: 50px auto;
    position: relative;
    width: 1024px;
    z-index: 1;
}
#obj {
    position: absolute;
    z-index: 2;
}

we should put our sphere object above our main canvas.

step 3. js

js/script.js

var canvas, ctx;
var canvasobj, ctxobj;
var idstw = 256;
var idsth = 256;
var ixspeed = 4;
var iyspeed = 3;
var ilastx = idstw / 2;
var ilasty = idsth / 2;
var oimage;
var amap = [];
var abitmap;

var mathsphere = function(px, py) {
    var x = px - idstw / 2;
    var y = py - idsth / 2;
    var r = math.sqrt(x * x + y * y);
    var maxr = idstw / 2;
    if (r > maxr) return {'x':px, 'y':py};

    var a = math.atan2(y, x);
    var k = (r / maxr) * (r / maxr) * 0.5 + 0.5;
    var dx = math.cos(a) * r * k;
    var dy = math.sin(a) * r * k;
    return {'x': dx + idstw / 2, 'y': dy + idsth / 2};
}

window.onload = function(){

    // load background
    oimage = new image();
    oimage.src="images/bg.jpg";
    oimage.onload = function () {

        // creating canvas and context objects
        canvas = document.getelementbyid('slideshow');
        ctx = canvas.getcontext('2d');
        canvasobj = document.getelementbyid('obj');
        ctxobj = canvasobj.getcontext('2d');

        // clear context
        ctx.clearrect(0, 0, ctx.canvas.width, ctx.canvas.height);

        // and draw source image
        ctx.drawimage(oimage, 0, 0);

        abitmap = ctx.getimagedata(0, 0, idstw, idsth);
        for (var y = 0; y < idsth; y++) {
            for (var x = 0; x < idstw; x++) {
                var t = mathsphere(x, y);
                amap[(x + y * idsth) * 2 + 0] = math.max(math.min(t.x, idstw - 1), 0);
                amap[(x + y * idsth) * 2 + 1] = math.max(math.min(t.y, idsth - 1), 0);
            }
        }

        // begin updating scene
        updatescene();
    };

    function updatescene() {

        // update last coordinates
        ilastx = ilastx + ixspeed;
        ilasty = ilasty + iyspeed;

        // reverse speed
        if (ilastx > ctx.canvas.width - idstw/2) {
            ixspeed = -3;
        }
        if (ilastx < idstw/2) {
            ixspeed = 3;
        }
        if (ilasty > ctx.canvas.height - idsth/2) {
            iyspeed = -3;
        }
        if (ilasty < idsth/2) {
            iyspeed = 3;
        }

        // shifting of the second object
        canvasobj.style.left = ilastx - math.floor(idstw / 2) + 'px';
        canvasobj.style.top = ilasty - (math.floor(idsth / 2)) + 'px';

        // draw result sphere
        var adata = ctx.getimagedata(ilastx - math.ceil(idstw / 2), ilasty - math.ceil(idsth / 2), idstw, idsth + 1);
        for (var j = 0; j < idsth; j++) {
            for (var i = 0; i < idstw; i++) {
                var u = amap[(i + j * idsth) * 2];
                var v = amap[(i + j * idsth) * 2 + 1];
                var x = math.floor(u);
                var y = math.floor(v);
                var kx = u - x;
                var ky = v - y;
                for (var c = 0; c < 4; c++) {
                    abitmap.data[(i + j * idsth) * 4 + c] =
                      (adata.data[(x + y * idsth) * 4 + c] * (1 - kx) + adata.data[((x + 1) + y * idsth) * 4 + c] * kx) * (1-ky) +
                      (adata.data[(x + (y + 1) * idsth) * 4 + c] * (1 - kx) + adata.data[((x + 1) + (y + 1) * idsth) * 4 + c] * kx) * (ky);
                }
            }
        }
        ctxobj.putimagedata(abitmap,0,0);

        // update timer
        settimeout(updatescene, 16);
    }
};

during initialization, the script prepares two canvas objects and two contexts. then, it loads our main background image, and draws it as our first context. then it prepares a hash table of sphere transformations: amap. and, in the end – it starts the timer, which updates the main scene. in this function (updatescene) we update the coordinates of our sphere object, and draw the updated sphere at our second location.


live demo

download in package


conclusion

i hope that today’s 3d html5 sphere lesson has been interesting for you. we have done another  nice html5 example. i will be glad to see your thanks and comments. good luck!

HTML

Published at DZone with permission of Andrey Prikaznov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Create a Resource Chart in JavaScript
  • Exploring Shadow DOM With Examples Using Cypress
  • Demystifying the ‘Class’ Attribute in HTML: A Comprehensive Guide With Examples
  • Cracking the Code: 7 Secrets Every Web Developer Should Know

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: