liveBook · Manning

2d context

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

A canvas rendering context that exposes a two-dimensional drawing API for painting onto a canvas.

To paint an image onto an HTML canvas, first get its 2D context. The context provides `drawImage`, which can select a source rectangle and place it in a destination rectangle. 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
  );
}

This function sets `globalAlpha` before drawing, so the image is painted with the requested transparency. section 34.2

Fade an image in

Draw the image repeatedly, increasing alpha by `(1 - alpha) / 24` each time. Stop at 0.99 opacity; otherwise, schedule the next draw with `requestAnimationFrame`. section 34.2

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

How deep it goes
Explains context setup, image placement, transparency, and a fade loop, but not the context's internals.
Examples
Demonstrates drawing an image across a canvas and fading it in through repeated animation frames.
What it assumes
Assumes an HTML canvas element and an ImageBitmap are available to draw.
What you can do after
Build from scratch a canvas image draw function and use it to animate a fade-in.
How it connects
Connects canvas drawing with ImageBitmap, drawImage, globalAlpha, and requestAnimationFrame.

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.