Chapter 16. Responsive Animation

Animation on the web is particularly nuanced, as we have to adjust our work to take into account bandwidth, code compatibility, and product design. In this chapter we’ll go over some techniques for creating a truly responsive scalable animation. We’ll also cover different ways of working with the animation to achieve positive user experiences and parity across our multidevice world.

Some Quick Responsive Tips

At the very least we should ensure that interaction also works well on mobile, but if we’d like to create interactions that take advantage of all of the gestures mobile has to offer, we can use libraries like ZingTouch or Hammer.js to work with swipe or multiple finger detection. With a bit of work, these interactions can all be created through native detection as well.

Responsive web pages can specify initial-scale=1.0 in the <meta> tag so that the device does not wait the default 300 ms for a second tap before calling the action. Interactions for touch events must either start from a larger touch target (40×40 px or greater) or use @media(pointer:coarse), as support allows.

GreenSock and Responsive SVG

The number-one reason I use GSAP has to do with cross-browser support for SVG transforms. Stable SVG rotation is very cumbersome. In almost every browser, transform-origin problems persist, and they are completely unsupported in IE. This problem is clearly exacerbated when attempting to use transforms in a responsive manner, as any small transform-origin anomalies are exaggerated and difficult to override.

Not only does GreenSock correct this behavior, but with support back to IE9, it offers a few more tools that make responsive design and development particularly solid. Currently, transforms on SVG elements with native rendering technologies (and subsequently, other JS libraries that use them) do not support correct rendering based on percentages. GSAP solves this issue with matrix calculations.

Let’s first establish that by removing the width and height values from the SVG itself, defining the viewBox, and then using CSS or JS to control the width and height of the SVG, we can easily make an SVG adjust to any kind of responsive implementation. You can also add preserveAspectRatio="xMinYMin meet" to ensure that all corresponding dimensions will scale appropriately and respective to one another, but since that’s the default, it’s not strictly necessary. There’s a great playground by Sara Soueidan if you’d like to get more background on the viewBox and scaling.

There are three other particular strengths that GSAP with respect to SVG, all employing the use of transforms. The first is that aside from transformOrigin, GSAP now has built-in support for svgOrigin. This means that you can choose whether you want your element to transform based on the element itself (i.e., rotating on its own axis) or using a coordinate in the SVG viewBox. With svgOrigin, you declare values according to the viewBox coordinates. In other words, if your viewBox is "0 0 400 400" and you want to spin around the SVG’s center, you would declare svgOrigin: "200 200". Usually you will find that moving and adjusting a transformOrigin is enough. But in the case of Figure 16-1 and its corresponding pen, I made a cow spin around the moon at a certain part of the viewBox, and because I used an svgOrigin coordinate it was very easy to make this animation responsive, spinning on one solid coordinate that’s stable no matter what size the SVG is:

TweenMax.set(cow, {
  svgOrigin:"321.05, 323.3",
  rotation:50
});
Figure 16-1. This SVG animation is draggable and pivots on a single point inside the SVG viewBox with svgOrigin, so it’s completely stable across responsive implementations (size the window down horizontally to watch the animation adjust to the viewport)

The next great feature we’ll cover is smoothOrigin on SVG elements. Typically, if you change the transform origin on elements after they’ve already been transformed, the movement becomes complex and counterintuitive, as seen in Figure 16-2 and its corresponding pen.

Figure 16-2. A pen showing that the spec’s interpretation of how stacking transforms behave is counterintuitive (courtesy of Marc Grabinski)

As explained in a video by Carl Schooff of GreenSock, smoothOrigin corrects for this problem. It makes sure that when you change the transform origin for an SVG element and subsequently move it again, it doesn’t cause any kind of strange jumpiness (which is what the spec will interpret).

This resolves a huge amount of counterintuitive and hair-pulling behavior when working with a longer and more complex responsive animation. GSAP also leaves you the option of turning this off with one line of code, in the edge case that you’d like to use the native rendering: CSSPlugin.defaultSmoothOrigin = false;.

The last great feature for complex responsive animations in GSAP is the ability to do percentage-based animations dependent on the SVG elements themselves. CSS and SMIL don’t have good support for this type of behavior. Just like with the BezierPlugin, GSAP offers the most backward compatibility and cross-browser support for percentage-based SVG transforms. Check out Figure 16-3, a pen courtesy of GreenSock:

var playBtn = document.getElementById("play"),
    tl = new TimelineMax({repeat:1, yoyo:true, paused:true});

tl.staggerTo(".box", 0.5, {x:"100%"}, 0.4)

play.onclick = function() {
  tl.restart();
}
Figure 16-3. GreenSock allows you to do percentage-based transforms on SVG elements, which is a really nice feature for responsive development

Responsive SVG, with or without GreenSock

Percentage-based  transforms on SVG elements are really impressive and useful. In responsive development, we make good use of flexbox, percentages, and units that allow us to scale or expand to fit containers. But even more amazing when you move to SVG is the fact that you might not need them. SVG transforms rely on the SVG canvas, not absolute, browser window–defined pixel integers. We’re moving our elements according to the SVG DOM. And elements aren’t the only thing that’s scalable. All of the corresponding transforms and movements are as well.

There are no media queries to be found. We move things based on the x- and y-axes, like so:

tl.staggerFromTo($iPop, 0.3, {
  scale: 0,
  x: 0,
  y: 0
}, {
  scale: 1,
  x: 30,
  y: -30,
  ease: Back.easeOut
}, 0.1, "start+=0.3")

Figure 16-4 and its corresponding demo show the result.

Figure 16-4. The animation changes size when you click the button, but the animation experience stays consistent

Note that we’re not moving things with percentage-based transforms. Our animation is establishing behavior based on the viewBox, and therefore, responsive development becomes as easy as removing the width and height and declaring it elsewhere.

It’s nice to just “squish” an animation to fit our viewport, but we all know that true responsive development is a more involved process than that. Let’s take our new shiny tools and couple them with some responsive development, from start to finish.

There are a few ways we can do this. One is to take a large SVG sprite and shift the viewBox with a media query event handler.

Responsive Reorganization by Updating the ViewBox

Do you remember when people used to use infographics? Infographics became very popular because of their impact on conversion. On the user side, they were full of quick, easy-to-digest information. They were colorful, and when created well, clearly illustrated comparative information that one could pick up at a glance. On the creator’s side, they increased the ROI (return on investment) of posts and shares. The impact of the graphics on a company’s visibility and brand awareness was staggering. The Whole Brain Blog boasted numbers such as:

  • Traffic to the website increased by over 400%
  • Leads increased by almost 4,500%
  • Number of new visitors to the site increased by almost 78%

But one thing all of these posts have in common is that they are at least two years old. If infographics have that kind of potential for performance, why do they seem to be considered a played out fad?

One possible reason is the tipping point for mobile. Infographics that are exciting and all-encompassing on the desktop become an arduous pinch-n-grab affair on a mobile device. With the rise of mobile traffic, sharing via social media causes frustration and a decline of the engagement potential of these images.

The next reason is a little simpler. When a concept doesn’t adjust to the present context, it fades away. With more interactivity and motion on the web, a static graphic doesn’t have the same pull as something that is more visually exciting, and here is where motion trumps all.

Animation shouldn’t be considered at the end of the design and development process; it should be the bones. If we marry that idea with the concept of conveying a lot of information visually, we can update the very basis of what an infographic is and does. I took the text content of an infographic I found in David McCandless’s book Knowledge Is Beautiful (Harper Design) and reimagined the look, feel, and implementation to create a responsive, animated infographic.

Please view the full pen that corresponds to Figure 16-5, as the embedded pen shows the collapsed view. Keep in mind that the progress of the text transitions is sped up here in order to demonstrate the animation, not necessarily the content.

Figure 16-5. The viewBox shifts for mobile and desktop views of the infographic

In terms of design, traditional infographics typically make use of a salon-style, visually loaded method. Here, we’ve still filled the usable image area but updated the design to feel a little more clean. We didn’t overload the graphic with many elements, because unlike with traditional static infographics, if there are too many different moving parts it’s disorienting for the viewer. It’s also heavier to load, so there is a performance hit.

In terms of responsive design, instead of having the entire presentation be fluid throughout, we had the infographic stay in place until a breakpoint, and then moved elements to different positions, allowing the main SVG to respond fluidly at that juncture. Even though we designed desktop-first, our media queries are a mobile-first implementation. I used an SVG that is very easy to make fluid, adjusting the viewport slightly on mobile with JavaScript:

var shape = document.getElementById("svg");

// media query event handler
if (matchMedia) {
  var mq = window.matchMedia("(min-width: 826px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}
// media query change
function WidthChange(mq) {
  if (mq.matches) {
    shape.setAttribute("viewBox", "0 0 765 587");
  } else {
    shape.setAttribute("viewBox", "0 0 592 588");
  }
};

We’re then animating it with GreenSock to take advantage of the both the timeline and the ability to scrub the animation to find different points in time to interact with on a slider. Here is an example of one piece of information in the graphic displaying on the timeline. Note that we’ve added a relative time for all of these animations to fire at using a label:

  tl.add("likely");
  tl.to($(".p1"), 0.3, {
      scale: 1.3,
      transformOrigin: "50% 100%",
      fill: $blue,
      ease: Bounce.easeOut
    }, "likely")
    .to($effect, 0.3, {
      y: -10,
      ease: Circ.easeOut
    }, "likely")
    .to($eLine, 0.3, {
      stroke: $orange,
      ease: Sine.easeOut
    }, "likely")
    .fromTo($(".d1"), 0.3, {
      opacity: 0,
      scale: 0.7
    }, {
      opacity: 1,
      scale: 1,
      ease: Back.easeOut
    }, "likely")
    .to($m1, 0.3, {
      fill: $green,
      ease: Circ.easeOut
    }, "likely");

We can improve the accessibility of the graphic by adding a <title> element. You can also supply an aria-labelledby attribute in the <svg> element to reinforce the relationship between these two elements:

<svg aria-labelledby="title" id="svg" xmlns="http://www.w3.org/2000/svg" 
     viewBox="0 0 765 587">
 <title id="title" lang="en">Circle of icons that illustrate Global Warming 
   Solutions</title>

If you need to, you can supply a title for any element in the SVG DOM. You can find more information on implementation in a great article by Dudley Storey. In the case of this demo, we kept the text separate so that it’s still completely legible to screen readers. This is an improvement over the original infographics, which, as static images, could not be accessed in this way.

This demo is merely a sketch, to ponder methods by which we can give shareable information more muscle with responsive animation. The same thing could also be achieved with PNGs, CSS, canvas, and variety of other methods. The potential that we have with the tools now supported on the web is exciting, and they can breathe new life into older concepts.

Responsive Reorganization with Multiple SVGs and Media Queries

We covered one solution for this in detail in Chapter 3. Another is to design our animation using interlocking parts, much like Tetris pieces, and use multiple SVGs that can be reconfigured. Let’s explore the latter, as shown in Figure 16-6 and its corresponding pen.

Figure 16-6. An interactive Huggy Laser Panda Factory

In the Huggy Laser Panda Factory pen, there are three distinct parts to the factory. In order to keep our code organized, each section can accept one type of user interaction, which then triggers its own timeline (Figure 16-7).

Figure 16-7. Each one of the SVGs interlocks and reconfigures, depending on the viewport size

Keeping the inline SVGs distinct from one another also allows us to collapse them and move them according to percentages or integers on variable viewports, making our animation flexible for both mobile and future iterations. We’ve plotted out an initial view for desktop, as well as how it will be reconfigured for smaller displays, including a transform: scaleX(-1); line to reflect the second portion on mobile so it will fit gracefully, with a mobile-first implementation:

@media (max-width: 730px) {
  .second {
    width: 70%;
    top: -90px;
    margin-left: 70px;
    transform: scaleX(-1);
  }
}


@media (min-width: 731px) {
  .second {
    width: 350px;
    margin-left: 365px;
    top: 370px !important;
  }
}

Each building block has its own function, named for what part of the animation it serves. This avoids any scoping problems and keeps everything organized and legible. The user can only trigger behaviors relative to the same SVG, or building block, of the animation. We pause the timeline initially, but use the button or group to restart it here:

// create a timeline but initially pause it so that we can control it via click
var triggerPaint = new TimelineMax({paused:true});
triggerPaint.add(paintPanda());

// this button kicks off the panda painting timeline
$("#button").on("click", function(e){
  e.preventDefault();
  triggerPaint.restart();
});

We also have a looping timeline that covers many elements in the document. We set a relative label to the beginning of it so that we can set loops on multiple objects. This is important because if we let loops follow one another in a timeline, only the first will fire, as it will run forever and the second one will wait to follow indefinitely:

function revolve() {
  var tl = new TimelineMax();

  tl.add("begin");
  tl.to(gear, 4, {
  transformOrigin:"50% 50%", 
  rotation:360, 
  repeat:-1, 
  ease: Linear.easeNone
}, "begin");
  tl.to(wind, 2, {
  transformOrigin:"50% 50%", 
  rotation:360, 
  repeat:-1, 
  ease: Linear.easeNone
}, "begin");

  // ...
  return tl;
}

var repeat = new TimelineMax();
repeat.add(revolve());

We now have four timelines in total: three that are cleanly associated with each section, and the global looping timeline. Our interaction and animations scale with each individual SVG, so we are free to move and adjust them in the configurations that we like for different viewports, and the code stays direct and organized.

Less Pizzazz on Mobile

Let’s face it, mobile connections (particularly in less-developed countries) can be pretty slow. Whether you only have a few key animation interactions on your site or a huge WebGL experience, sometimes an animation that looks beautiful on desktop need not scale down to a mobile experience.

In the case of a large canvas animation, or even a really complex SVG animation that is not critical to the user experience, sometimes the best thing you can do is to tone it down or turn it off for smaller devices.

Active Theory’s site does a beautiful job of this (see Figure 16-8) by showing you a full particle canvas animation on desktop, which is replaced with a simple polygon background on mobile. The interactions on mobile are still very on-point, transitioning beautifully beyond even what we expect on native.

Figure 16-8. Active Theory keeps its visual language consistent, while dropping heavy canvas animations on mobile

The team still shows off its interaction prowess in the way you navigate the site, which is arguably more impressive on mobile than an animated background would be anyway. The design saves the bandwidth for what counts.

Have a Plan

Whether you design for responsiveness from start to finish or simply turn animations off on mobile, having a concrete plan for what your viewers experience from device to device is vital. This is particularly true in a landscape where mobile is king. Content, type of image, and user bandwidth should all help guide animation choices for responsive design.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.216.249