liveBook · Manning

getImageData()

As explained in D3.js in Action, Third Edition

getImageData() is a Canvas 2D context method that returns pixel data for a specified rectangular region of a canvas.

getImageData() is a Canvas 2D context method for reading pixel data from a rectangular canvas region. In an interaction layer, a 1×1 rectangle at the mouse position reveals the pixel’s color, which can identify the visual object underneath. section 15.4

A Canvas interaction strategy uses getImageData() in a short pipeline:

  • Read the first three values of data as RGB components, build the matching color string, and look up the node in the Map. section 15.4

Detecting a hovered painting circle

A hidden canvas duplicates the painting circles with unique colors. When the pointer moves, getImageData() samples one pixel at the pointer location. The resulting RGB color retrieves the corresponding painting, allowing a tooltip to display its title, link, and position. If the canvas was scaled for the screen’s resolution, multiply the event coordinates by window.devicePixelRatio before sampling.

How D3.js in Action, Third Edition covers it

How deep it goes
Explains a working hidden-canvas hit-testing implementation, including 1-pixel sampling, RGB extraction, coordinate scaling, and lookup.
Examples
Uses uniquely colored painting circles on a hidden canvas to detect hovered nodes and show painting tooltips.
What it assumes
Assumes Canvas drawing, mouse events, RGB colors, and Map usage while demonstrating the interaction strategy progressively.
What you can do after
Apply it via the Canvas API to identify hovered visualization objects and retrieve their associated data.
How it connects
Connects Canvas 2D API, hidden canvas, mouse events, RGB colors, Map, tooltips, and data visualization.

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.