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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • How to Verify Domain Ownership: A Technical Deep Dive
  • Make Static Sites Feel Dynamic With APIs Only (No Backend Needed)
  • Accessibility Basics for Building Telehealth Platforms With React Code Examples

Trending

  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • YAGNI in the Age of AI Coding
  • How to Migrate From LangChainGo to Genkit Go
  • Should Developers Switch From SQLite to DuckDB?

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. HTML5 Canvas 3D Sphere

HTML5 Canvas 3D Sphere

By 
Andrei Prikaznov
·
Apr. 18, 12 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
12.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in
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 Andrei Prikaznov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • How to Verify Domain Ownership: A Technical Deep Dive
  • Make Static Sites Feel Dynamic With APIs Only (No Backend Needed)
  • Accessibility Basics for Building Telehealth Platforms With React Code Examples

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook