liveBook · Manning

Bitmap image

As explained in D3.js in Action, Third Edition

A raster graphic is an image represented as a grid of discrete pixels.

A bitmap image, also called a raster graphic, represents an image as a grid of discrete pixels. Canvas produces bitmap images through imperative JavaScript drawing commands, unlike SVG, which uses vector graphics and a declarative approach. section 15.2.1 section 15.1

Bitmap rendering becomes useful when a visualization needs:

  • High performance for large numbers of visual elements, complex animations, or intricate color gradients. section 15.1
  • Careful resolution management, because bitmap graphics can blur when zoomed or displayed on high-resolution screens. section 15.1
  • A mixed SVG-Canvas design when SVG accessibility, styling, or element-level interaction should complement Canvas performance. section 15.5

Responsive Canvas rendering

A responsive Canvas can take its dimensions from its parent container, multiply them by window.devicePixelRatio, and update them on resize. Its 2D context can then be scaled by the same ratio so the bitmap remains sharp on dense displays. section 15.2.1 section 15.2.1

Listing 15.3 Correcting the resolution (main.js)
const canvas = d3.select("#canvas")
  .append("canvas")
    .style("border", "1px solid black")
    .style("max-width", "100%");  #1


const container = document.querySelector("#canvas");
const devicePixelRatio = window.devicePixelRatio;  #2

const setCanvasSize = () => {
  const width = container.offsetWidth;
  const height = 0.333 * width;

  canvas
    .attr("width", width * devicePixelRatio)     #3
    .attr("height", height * devicePixelRatio); 
};

setCanvasSize();
window.addEventListener("resize", setCanvasSize);

Inspect the complete responsive-resolution pattern, including CSS sizing, device-pixel scaling, and resize handling. section 15.2.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains pixels, SVG trade-offs, responsive sizing, device density, and context scaling, but defers detailed drawing APIs.
Examples
Uses responsive Canvas elements, pixel-density correction, animated visualizations, gradients, and mixed SVG-Canvas projects.
What it assumes
Assumes basic web-page and JavaScript familiarity while teaching Canvas raster behavior and sizing from the ground up.
What you can do after
Operate/configure Canvas dimensions and resolution for responsive bitmap visualizations.
How it connects
Connects bitmap images with Canvas, SVG, JavaScript, the DOM, devicePixelRatio, and mixed-mode rendering.

Also explained in

Compare how 4 books explain bitmap image →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.