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 Twirl Sphere

HTML5 Canvas Twirl Sphere

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
May. 04, 12 · Web Dev Zone · Interview
Like (0)
Save
Tweet
4.42K Views

Join the DZone community and get the full member experience.

Join For Free
today, i would like to show you how to create an animated twirl sphere (i modified our previous 3d sphere, and i used same way of accessing pixels on the canvas). our sphere goes around the canvas continuously. this example is a cross browser solution (because it uses html5).

in the end, you should get something like this:

html5 canvas twirl sphere

here are our demo and downloadable package:

live demo

download in package


ok, please download our 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="630"></canvas>
    <canvas id="obj" width="256" height="256"></canvas>
</div>

i prepared two canvas objects: the first for the resource image, and the second – for our twirl sphere.

step 2. css

css/main.css

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

we should keep our sphere object above our main canvas.

step 3. js

and now, our main js script file:

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 amapt = [];
var abitmap;

var mathtwirl = 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, 't': 1};

    var a = math.atan2(y, x);
    a -= 1 - r / maxr;

    var dx = math.cos(a) * r;
    var dy = math.sin(a) * r;

    return {'x': dx+idstw/2, 'y': dy+idsth/2, 't': 1.5}
}

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 = mathtwirl(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);
                amapt[(x + y * idsth)] = t.t;
            }
        }

        // begin updating scene
        updatescene();
    };

    function updatescene() {

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

        // reverse speed
        if (ilastx + 1 > ctx.canvas.width - idstw/2) {
            ixspeed = -4;
        }
        if (ilastx - 1 < idstw/2) {
            ixspeed = 4;
        }
        if (ilasty + 1 > ctx.canvas.height - idsth/2) {
            iyspeed = -3;
        }
        if (ilasty - 1 < 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 twirl 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 t = amapt[(i + j * idsth)];
                var x = math.floor(u);
                var y = math.floor(v);
                var kx = u - x;
                var ky = v - y;
                for (var c = 0; c < 3; 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) * t +
                      (adata.data[(x + (y + 1) * idsth) * 4 + c] * (1 - kx) + adata.data[((x + 1) + (y + 1) * idsth) * 4 + c] * kx) * (ky) * t;
                }
            }
        }
        ctxobj.putimagedata(abitmap,0,0);

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

during initialization, the script prepares two canvas objects and two contexts. after initialization, it loads the background image, and drasw it at our first context. then it prepares a hash table for sphere transformations: amap (using the new mathtwirl function). and, finally – it starts the timer that updates the main scene. this function (updatescene) updates the coordinates of our sphere object, and draws the updated sphere at our second context.


live demo

download in package


conclusion

i hope that today’s twirl html5 sphere lesson has been interesting for you. we have finished 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

  • Stupid Things Orgs Do That Kill Productivity w/ Netflix, FloSports & Refactoring.club
  • Testing Under the Hood Or Behind the Wheel
  • What Is ERP Testing? - A Brief Guide
  • Debugging the Java Message Service (JMS) API Using Lightrun

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