liveBook · Manning

drawImage

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

A canvas context method that draws an image or portion of an image onto the canvas.

Want to paint an image into a canvas gallery? Get the canvas’s 2D context, then call drawImage with the image and the source and destination rectangles. 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 the whole image across the whole canvas: the first rectangle selects the source image area; the second sets where it appears on the canvas. section 34.2

The eight rectangle values are source x, y, width, height, followed by destination x, y, width, height. Change the source rectangle to select part of an image, or the destination rectangle to control the canvas area it fills. To fade an image in, set the context’s globalAlpha before drawing and redraw it with increasing opacity. section 34.2

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

How deep it goes
Explains the source and destination rectangles and alpha-based drawing, without detailing implementation internals.
Examples
Uses a gallery function that stretches an image across the canvas and a draw function that accepts alpha.
What it assumes
Assumes an image and HTML canvas; demonstrates obtaining the canvas element and its 2D context.
What you can do after
Apply the Canvas 2D API to draw an image or image region onto a canvas and adjust its opacity.
How it connects
Connects HTML canvas and its 2D context with ImageBitmap, globalAlpha, and image fading.

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.