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 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
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
  1. DZone
  2. Coding
  3. JavaScript
  4. Sexy animated spirographs in 35 sloc of d3.js

Sexy animated spirographs in 35 sloc of d3.js

Swizec Teller user avatar by
Swizec Teller
·
Mar. 08, 13 · Interview
Like (0)
Save
Tweet
Share
22.23K Views

Join the DZone community and get the full member experience.

Join For Free
you probably remember spirographs as kid’s toys from your youth. i had a simple set that was just a collection of plastic sprockets with holes for pencils.

endless amounts of fun when i was two or three years old. i think … i don’t really remember much from that time, but i remember having those thingies and loving playing with them. one of my earliest memories even!

spirograph

spirograph

last night i was making an animation example for the d3.js book i’m writing and ended up with the idea of progressively drawing out cool looking parametric equations. little did i know, those are actually spirographs! learned something while i was learning something.

@ swizec parametric equations are a way to model physical spirographs. en.wikipedia.org/wiki/spirograph

— klemen slavič (@krofdrakula) march 6, 2013

my failure in common knowledge aside, it’s possible to animate the drawing of parametric equations with just a few lines of d3.js code. what i’m about to show you has a pretty big problem, but produces cool looking results “in the lab”. try to guess what the problem is.

animating spirographs

after a few steps

after a few steps

we’ll make an animation timer and for each tick we’ll draw a new step of the spirograph. after the spirograph is finished, we’ll stop the timer. to make the animation more interesting to watch, we’ll also fake a brush flying around (just a black dot).

we start with some basic html:

<!doctype html>
<title></title>
<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
 
<div id="graph"></div>
 
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="timers.js"></script>

then we hop into the javascript to flesh out the actual code.

var width = 600,
    height = 600,
    svg = d3.select('#graph')
        .append('svg')
        .attr({width: width,
               height: height});

i found the parametric function in the wikipedia’s article on parametric equations. we’ll be giving it a simple parameter calculated from the animation timer and it will return a two dimensional position.

var position = function (t) {
    var a = 80, b = 1, c = 1, d = 80;
 
    return {x: math.cos(a*t) - math.pow(math.cos(b*t), 3),
            y: math.sin(c*t) - math.pow(math.sin(d*t), 3)};
};

tweaking the a , b , c, and d parameters will change the final shape.

next we’re going to define some scales to help us translate between maths space and our drawing space.

var t_scale = d3.scale.linear().domain([500, 30000]).range([0, 2*math.pi]),
    x = d3.scale.linear().domain([-2, 2]).range([100, width-100]),
    y = d3.scale.linear().domain([-2, 2]).range([height-100, 100]);
 
var brush = svg.append('circle')
        .attr({r: 4}),
    previous = position(0);

the t_scale is going to translate time into a parameter, x and y calculate proper positions on the final image using the coordinates returned by the position function.

we also put a simple circle on the image – this will represent the brush – and we need to take note of the previous position so we can draw lines between our current and previous state.

var step = function (time) {
    if (time > t_scale.domain()[1]) {
        return true;
    }
 
    var t = t_scale(time),
        pos = position(t);
 
    brush.attr({cx: x(pos.x),
                cy: y(pos.y)});
    svg.append('line')
        .attr({x1: x(previous.x),
               y1: y(previous.y),
               x2: x(pos.x),
               y2: y(pos.y),
               stroke: 'steelblue',
               'stroke-width': 1.3});
 
    previous = pos;
};

this is our step function . it draws every consecutive step of the animation by moving the brush and putting a line between the current and previous position. the animation will stop when this function returns true so we make sure the time parameter doesn’t go beyond t_scales ‘s domain.

finally, we simply start the timer.

var timer = d3.timer(step, 500);

the timer will start running after 500 milliseconds and repeatedly call the step function until it returns true.

you can check the animation out via the magic of github pages . the final spirograph looks like this:

a parametric equation visualised

a parametric equation visualised

figured out the problem yet?

the problem with this approach is that i’m using the animation timer itself as a parameter to the function, which means point density depends on how long you’re willing to let the animation run. it will always draw the complete function because of how d3 scales work, but it might look very approximate. think squares for circles approximate.

another problem is that using a slower computer, or doing anything that lags the cpu even a little bit while the animation is running will ruin the final picture.

for instance, this is what happens when i switch desktops around while the browser is drawing.

glitchy spirograph

glitchy spirograph


D3.js

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Real-Time Supply Chain Control Tower Powered by Kafka
  • Why Does DevOps Recommend Shift-Left Testing Principles?
  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • Using JSON Web Encryption (JWE)

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

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

Let's be friends: