Quantcast
Channel:   eSolution Inc   » point
Viewing all articles
Browse latest Browse all 114

Introducing Jelly Navigation Menu: When Canvas Meets PaperJS

$
0
0

Introducing Jelly Navigation Menu: When Canvas Meets PaperJS

It’s our great pleasure to support active members of the Web design and development community. Today, we’re proud to present the Jelly Navigation Menu that shows the power of PaperJS and TweenJS when used together. This article is yet another golden nugget of our series of various tools, libraries and techniques that we’ve published here on Smashing Magazine: LiveStyle, PrefixFree, Foundation, Sisyphus.js, GuideGuide, Gridpak, JS Bin and CSSComb. — Ed.

There is no doubt that the Web helps designers and developers find the best inspiration and resources for their projects. Even though there are a bunch of different tutorials and tips available online, I feel that HTML5 canvas techniques are missing the most. Good news: I had the chance to fulfill this wide gap. In this article, I would like to share my experience and story of how I brought the “Jelly Navigation Menu” to life. Credits go to Capptivate.co and Ashleigh Brennan’s icons — they were my inspiration for this project.

Before We Start

The source code for this project was originally written in CoffeeScript — I believe it’s a better way to express and share JavaScript code that way. I will refer to CoffeScript’s source in code sections within this post and you’ll also notice links to CodePens that have been rewritten in JavaScript and represent local parts of code as well. I recommend downloading the source code on GitHub so you can easily follow me while I explain the necessary code in detail.

I used PaperJS for the canvas graphics and TweenJS for the animations. Both of them tend to freak out some folks, but don’t worry, they are really intuitive and easy to understand. If you’d like to learn how to set up PaperJS and TweenJS environments, you can fork this cool bootstrap pen for online fun or this git repo if you want to experiment locally.

 Introducing Jelly Navigation Menu: When Canvas Meets PaperJS
A preview of the Jelly Navigation Menu.

See Full Demo

First Step: Changing The Section Shape

Our first aim is to change the menu section shape by manipulating the curves. Every object is made up of anchor points. These points are connected with each other by curves. So each point has “In” and “Out” handles to define the location and direction of specific curves. Folks who work with vector editors should feel comfortable with this step.

 Introducing Jelly Navigation Menu: When Canvas Meets PaperJS
In Paper.js, paths are represented by a sequence of segments that are connected by curves. A segment consists of a point and two handles, defining the location and direction of the curves. See the handles in action.

All we need to do is to change the <code>handleOutcode> position of the <code>top-leftcode> and <code>bottom-rightcode> points. To achieve this, I wrote simple so-called “toppie” and “bottie” functions:

<code class="language-javascript">toppie:(amount)->
  @base.segments[1].handleOut.y = amount
  @base.segments[1].handleOut.x = (@wh/2)

bottie:(amount)->
  @base.segments[3].handleOut.y = amount
  @base.segments[3].handleOut.x = - @wh/2

# @wh/2 is section center.
# @base variable holds section's rectangle path.code>

It’s important to set the handle’s X position to exactly the middle of the section, so that the curve will turn out to be symmetrical.

See Demo #1

Second Step: Calculating The Scrolling Speed

So the next thing that needs to be done is to calculate the scrolling speed and direction, and then pass this data to the <code>bottiecode> and <code>toppiecode> functions. We can listen to the container’s scrolling event and determine the current scrolling position (in my case the “container” is a <code>#wrappercode> element whereas it is a window object in the pen examples).

<code class="language-javascript"># get current scroll value
window.PaperSections.next = window.PaperSections.$container.scrollTop()

# and calculate the difference with previous scroll position
window.PaperSections.scrollSpeed = (window.PaperSections.next - window.PaperSections.prev)

# to make it all work, all we have left to do is to save current scroll position to prev variable
window.PaperSections.prev = window.PaperSections.nextcode>

This is repeated for every scrolling event. In this code snippet, <code>window.PaperSectionscode> is just a global variable. I also made a few minor additions in my implementation:

  • A silly coefficient to increase scroll speed by multiplying it by <code>1.2code> (just played around with it),
  • I sliced the scroll speed result by its maximum so that it is not larger than <code>sectionHeight/2code>,
  • I also added a direction coefficient (it could be <code>1code> or <code>-1code>, you can change it in <code>dat.guicode> on the top right of the page). This way you can control the reaction direction of sections.

Here is the final code:

<code class="language-javascript">if window.PaperSections.i % 4 is 0
  direction = if window.PaperSections.invertScroll then -1 else 1
  window.PaperSections.next = window.PaperSections.$container.scrollTop()
  window.PaperSections.scrollSpeed = direction*window.PaperSections.slice 1.2*(window.PaperSections.next - window.PaperSections.prev), window.PaperSections.data.sectionheight/2
  window.PaperSections.prev = window.PaperSections.next
  window.PaperSections.i++code>

In this example, <code>if window.PaperSections.i % 4 is 0code> helps us react on every fourth scroll event — similar to a filter. That function lives in <code>window.PaperSections.scrollControlcode>.

That’s it! We’re almost done! It couldn’t be any easier, right? Try out the scrolling here.

See Demo #2

Step Three: Make It Jelly!

In this final step, we need to animate the <code>toppiecode> and <code>bottiecode> functions to <code>0code> with TweenJS’ elastic easing everytime the scrolling stops.

3.1 Determine When Scrolling Stops

To do this, let’s add the <code>setTimeoutcode> function to our <code>window.PaperSections.scrollControlcode> function (or <code>scrollcode>) with 50ms delay. Each time when the scrolling event fires up, the Timeout is cleared except for the last one, i.e. once scrolling stops, the code in our timeout will execute.

<code class="language-javascript">clearTimeout window.PaperSections.timeOut
window.PaperSections.timeOut = setTimeout ->
  window.PaperSections.$container.trigger 'stopScroll'
  window.PaperSections.i = 0
  window.PaperSections.prev = window.PaperSections.$container.scrollTop()
    , 50code>

The main focus here is the <code>window.PaperSections.$container.triggercode> <code>stopScrollcode> event. We can subscribe to it and launch the animation appropriately. The other two lines of code are simply being used to reset helper variables for later <code>scrollSpeedcode> calculations.

See Demo #3

3.2 Animate Point’s handleOut To “0”

Next, we’ll write the <code>translatePointYcode> function to bring our jelly animation to life. This function will take the object as a parameter with the following key-value sets:

<code class="language-javascript">{
  // point to move (our handleOut point)
  point: @base.segments[1].handleOut,

  // destination point
  to: 0,

  // duration of animation
  duration: duration
}code>

The function body is made up of the following:

<code class="language-javascript">translatePointY:(o)->
  # create new tween(from point position) to (options.to position, with duration)
  mTW = new TWEEN.Tween(new Point(o.point)).to(new Point(o.to), o.duration)

  # set easing to Elastic Out
  mTW.easing TWEEN.Easing.Elastic.Out
        
  # on each update set point's Y to current animation point
  mTW.onUpdate ->
    o.point.y = @y

  # finally start the tween
  mTW.start()code>

The <code>TWEEN.update()code> function also has to be added to every frame of the PaperJS animation loop:

<code class="language-javascript">onFrame = ->
  TWEEN.update()code>

Also, we need to stop all animations on scrolling. I added the following line to the scroll listener function:

<code class="language-javascript">TWEEN.removeAll()code>

Finally, we need to subscribe to the <code>stopScrollcode> event and launch the animations by calling our <code>translatePointYcode> function:

<code class="language-javascript">window.PaperSections.$container.on 'stopScroll', =>
  # calculate animation duration
  duration = window.PaperSections.slice(Math.abs(window.PaperSections.scrollSpeed*25), 1400) or 3000

  # launch animation for top left point
  @translatePointY(
    point:      @base.segments[1].handleOut
    to:           0
    duration: duration
  ).then =>
    # clear scroll speed variable after animation has finished
    # without it section will jump a little when new scroll event fires
    window.PaperSections.scrollSpeed = 0
         
  # launch animation for bottom right point
  @translatePointY
    point:      @base.segments[3].handleOut
    to:           0
    duration: durationcode>

Et voilà!

See Demo #4

Note: In my source code of the <code>translatePointYcode> function, I added a deferred object for chaining, optional easing and onUpdate function. It is omitted here for the sake of simplicity.

In Conclusion

Last but not least, a class for the sections has to be added. Of course, you can make as many instances of it as you like; you just need to define initial Y offset and colors. Also, you will need to make sure that the section in your layout has the same height as the section in canvas. Then we can just apply <code>translated3dcode> to both on the <code>scrollcode> event and animations. This will cause HTML sections to move properly, just like the canvas sections, and hence produce a realistic animation.

 Introducing Jelly Navigation Menu: When Canvas Meets PaperJS

The reason why we need to use <code>translate3dcode> instead of <code>translateYcode> is to make sure that Webkit rendering engines use hardware acceleration while rendering them, so we do not drop out of the 60fps animation budget. But keep your eyes wide open if your sections contain any text. 3D transforms will drop anti-aliasing from subpixel to grayscale, so it may look a bit blurry!

Feedback

I look forward to your thoughts, questions and/or your feedback to the Jelly Navigation Menu in the comments section below. You can also reach out to me via Twitter anytime!

(vf) (il)




Viewing all articles
Browse latest Browse all 114

Trending Articles