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

Livecoding: canvas.drawImage Performance Is Weird but Magical

Want to put some animations in your web application? Read on to learn how to use JavaScript to implement time based physics and make your animation smooth.

Swizec Teller user avatar by
Swizec Teller
·
May. 19, 17 · Tutorial
Like (3)
Save
Tweet
Share
4.88K Views

Join the DZone community and get the full member experience.

Join For Free

this week, i had the charisma of a peeled potato. the live stream started with 6 people in the chat, and it ended with 2. usually, it ends with … more.

so sad.

but! we learned stuff about canvas.drawimage , and i poked around after the stream and made this glorious thing. 14,000 smoothly animated particles!

14,000 animated particle minions

cool, huh? such a shame it didn’t work during the stream. then 3 people would’ve stayed!

the first thing we tried was the concept of sprites. instead of doing .arc and .stroke for every particle, you do it once, then copy-paste that particle into other places like this:

// draw a sprite particle in componentdidmount
this.context.beginpath();
this.context.arc(1.5, 1.5, 1, 0, 2*math.pi, false);
this.context.stroke();

// copy pasta particle

drawparticle(particle) {
   let { x, y } = particle;

   this.context.drawimage(this.canvas, 0, 0, 3, 3, x, y, 3, 3);
}

using .drawimage like this tells canvas to take pixels from the top left corner and copy them to a new place. a fast operation in theory, but something went wrong for us.

slow drawimage

terrible. even worse than before. copying those few pixels thousands of times grinds our animation to a halt. with a few thousand elements, each frame render takes a few seconds.

but at least the .drawimage approach makes it easy to render arbitrary images instead of particles. instead of using this.canvas as the source, you can use an arbitrary image() object, which you can fill with an image from any url on the internet.

minion sprites

strange … that feels smoother, doesn’t it? i’m not going crazy, right?

anyway, there’s only one thing left to do: decouple physics from frame rate. a big part of why the animation feels so slow is that we only calculate new particle positions once per frame, which makes sense because we’re only drawing them once per frame.

our frame rate is not up to snuff for that. we’re dropping frames, so we have to compensate for that in our calculation. the idea is that for each drawn frame, we have to pretend like multiple physics frames happened.

fixing physics happens in the reducer and looks like this:

// reducer

case ‘time_tick’:
        let {svgwidth, svgheight, lastframetime} = state,
            newframetime = new date(),
            multiplier = (newframetime-lastframetime)/(1000/60); // n frames dropped

        let movedparticles = state.particles
                                  .filter((p) => {
                                      return !(p.y > svgheight || p.x < 0 || p.x > svgwidth);
                                  })
                                  .map((p) => {
                                      let [vx, vy] = p.vector;
                                      p.x += vx*multiplier;
                                      p.y += vy*multiplier;
                                      p.vector[1] += gravity*multiplier;
                                      return p;
                                  });

        return object.assign({}, state, {
            particles: movedparticles,
            lastframetime: new date()
        });

we start by tracking timestamps for each frame and calculating a multiplier. then, we multiply every position and vector change with the multiplier and voilà: time-based (instead of frame-based) physics.

time-based physics

so smooth! i had to increase the number of particles generated on every animation tick up to 2000 just to see if anything interesting going on. insane.

mission accomplished, right? it’s smooth up to 8,000 particles, and we can’t push it to put more than that on-screen.

i wonder what happens if we put the minion sprite and the better physics together.

physics minions

ho boy! 14,000 smoothly animated minions!

with a production build and a big screen, you can reach over 20,000 minions on screen, and it still looks smooth. try it.

i have no idea why it’s faster to drawimage a complex.png than a circle. or why it’s faster to drawimage an image() object than a part of the canvas. it makes no sense, but here we are.

do you know?

Frame (networking)

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

  • 7 Awesome Libraries for Java Unit and Integration Testing
  • What Is a Kubernetes CI/CD Pipeline?
  • Bye Bye, Regular Dev [Comic]
  • How to Create a Real-Time Scalable Streaming App Using Apache NiFi, Apache Pulsar, and Apache Flink SQL

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: