liveBook · Manning

Canvas element

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

An HTML element that provides a scriptable bitmap drawing surface for web graphics.

Need to paint an image in a web gallery? The HTML canvas element provides a drawing surface: get the element, then its 2D context. Use that context to draw images onto the canvas. section 34.2

function draw(img) {                                  1
  const gal = document.getElementById('gallery');
  const ctx = gal.getContext('2d');
  ctx.drawImage(img,                                  2
    0, 0, img.width, img.height,
    0, 0, gal.width, gal.height
  );
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":54},{\"line\":0,\"ch\":55}],[{\"line\":2,\"ch\":30},{\"line\":2,\"ch\":31}],[{\"line\":3,\"ch\":54},{\"line\":3,\"ch\":55}]]"}
!@%STYLE%@!

This function draws an image across the canvas: the source coordinates select the image area, and the destination coordinates set the canvas area. section 34.2

Fade an image in

Set the context’s globalAlpha before drawing. Then repaint the image over successive animation frames, increasing alpha until it is nearly 1. 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 drawing and alpha-based fading, without detailing canvas internals.
Examples
Draws an image across a gallery canvas, then fades it in by increasing alpha over animation frames.
What you can do after
Apply the Canvas 2D context to draw images and create a fade-in effect.
How it connects
Connects the canvas element to the Canvas 2D context, drawImage, ImageBitmap, globalAlpha and requestAnimationFrame.

Also explained in

Compare how 4 books explain canvas element →

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.