liveBook · Manning

Alpha channel

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

The transparency component of a color or image, typically represented as an opacity value from fully transparent to fully opaque.

To fade an image onto a canvas, set the context’s `globalAlpha` before drawing it. Start with low opacity, increase alpha on each animation frame, and stop at 0.99; a promise can resolve when the fade finishes. section 34.2

function fade(image) {
  return new Promise(resolve => {                             1
    function fadeIn(alpha) {                                  2
      draw(image, alpha);                                     3
      if (alpha >= .99) {
        resolve();                                            4
      } else {
        alpha += (1-alpha)/24;                                5
        window.requestAnimationFrame(() => fadeIn(alpha));    5
      }
    }
    fadeIn(0.1);                                              6
  });
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":62},{\"line\":1,\"ch\":63}],[{\"line\":7,\"ch\":18},{\"line\":7,\"ch\":19}],[{\"line\":11,\"ch\":13},{\"line\":11,\"ch\":14}],[{\"line\":2,\"ch\":62},{\"line\":2,\"ch\":63}],[{\"line\":7,\"ch\":27},{\"line\":7,\"ch\":28}],[{\"line\":3,\"ch\":62},{\"line\":3,\"ch\":63}],[{\"line\":5,\"ch\":62},{\"line\":5,\"ch\":63}],[{\"line\":7,\"ch\":28},{\"line\":7,\"ch\":29}],[{\"line\":7,\"ch\":62},{\"line\":7,\"ch\":63}],[{\"line\":8,\"ch\":62},{\"line\":8,\"ch\":63}],[{\"line\":7,\"ch\":62},{\"line\":7,\"ch\":63}],[{\"line\":8,\"ch\":62},{\"line\":8,\"ch\":63}],[{\"line\":11,\"ch\":62},{\"line\":11,\"ch\":63}]]"}
!@%STYLE%@!

The fade starts at 0.1, redraws with increasing alpha, and resolves its promise at 0.99. section 34.2

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Implements alpha-based redrawing with requestAnimationFrame and promise completion, without detailing rendering internals.
Examples
Demonstrates fading a gallery image from alpha 0.1 to 0.99.
What you can do after
Apply alpha to canvas images and signal fade completion with a promise.
How it connects
Connects canvas drawing with globalAlpha, requestAnimationFrame, and Promises.

Also explained in

Compare how 3 books explain alpha channel →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.