DZone
Web Dev Zone
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
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > HTML5 Canvas 3D Sphere

HTML5 Canvas 3D Sphere

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
Apr. 18, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
10.52K 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.

Popular on DZone

  • Portfolio Architecture Examples: Retail Collection
  • Federated Schema Design
  • Augmented Analytics: The Future of Business Intelligence
  • A First Look at CSS When and Else Statements

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo