liveBook · Manning

globalAlpha

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

A canvas context property that sets the global transparency used for subsequent drawing operations.

Want a canvas image to fade in? Set the context’s globalAlpha before drawing: it applies transparency to what the context paints. section 34.2

function draw(img, alpha=1) {
  const gal = document.getElementById('gallery');
  const ctx = gal.getContext('2d');
  ctx.globalAlpha = alpha;
  ctx.drawImage(img,
    0, 0, img.width, img.height,
    0, 0, gal.width, gal.height
  );
}

The draw function accepts an alpha value and assigns it to the context before drawing the image. With no value supplied, it uses 1. section 34.2

Fade an image in

Draw the image at its current alpha, then increase alpha by `(1-alpha)/24` and redraw on the next animation frame. Stop at `.99`; the transition can resolve a promise when it finishes. section 34.2

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

How deep it goes
Explains setting alpha before drawing and demonstrates repeated redraws, without detailing other context properties.
Examples
Uses a canvas image gallery and a recursive fade-in that increases alpha until it reaches .99.
What you can do after
Build a canvas image fade-in by redrawing at increasing alpha and resolving a promise when it completes.
How it connects
Connects canvas drawing with drawImage, requestAnimationFrame, and promises.

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.