> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.doc-detective.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.doc-detective.com/_mcp/server.

# Find elements by image

> Locate an icon, canvas drawing, or custom-drawn control by what it looks like, then click it, type into it, drag it, crop to it, or annotate it.

Selectors and text can't reach what a page draws rather than structures, such as an icon with no label, a canvas, or a chart. With `elementImage`, you give Doc Detective a picture of the target, and it looks for that picture on screen.

If the target has text or an accessible name, reach for those first. They survive restyling, and an image doesn't.

## Before you begin

Make sure you have the following:

* [Doc Detective installed](/docs/get-started/installation).
* A test that runs in Chrome or Firefox on a desktop.
* A page with the target you want to find. The examples below use a local test page at `http://localhost:8092`. Replace its URL, selectors, and file names with your own.

Doc Detective installs the image matcher, `@appium/opencv`, the first time a run needs it.

## Step 1: Choose a reference image

For an icon, use the icon's own file, with a transparent background. Your design system or icon library already has it.

For anything else, crop a reference from a screenshot with a `screenshot` step. Then remove the step, or set its `overwrite` to `"false"`, so that later runs don't replace the reference.

**`capture-reference.spec.json`**

```json title="capture-reference.spec.json"
{
  "tests": [
    {
      "steps": [
        { "goTo": "http://localhost:8092/find-image.html" },
        {
          "screenshot": {
            "path": "chart.png",
            "crop": { "selector": "#sample-chart" }
          }
        }
      ]
    }
  ]
}
```

A reference can be a PNG, JPEG, or SVG.

## Step 2: Find it

Name the reference in `elementImage`:

**`find-by-image.spec.json`**

```json title="find-by-image.spec.json"
{
  "tests": [
    {
      "steps": [
        { "goTo": "http://localhost:8092/find-image.html" },
        { "find": { "elementImage": "icons/save.svg" } },
        { "click": { "elementImage": "icons/save.svg" } },
        { "find": { "elementImage": "chart.png" } }
      ]
    }
  ]
}
```

`elementImage` takes a path, or an object with either a `path` or a `base64` value, and an optional `threshold` and `color`.

A relative path resolves the way every other path in a spec does, against the spec file unless you've set `relativePathBase` to `cwd`.

To keep a small reference inside the spec, give its bytes as base64:

```json
{ "find": { "elementImage": { "base64": "iVBORw0KGgoAAAANSUhEUgAA..." } } }
```

The `base64` value works with or without a `data:image/png;base64,` prefix.

A failed step's message leaves the value out. Results repeat the step as you wrote it, so a long value makes them longer. Prefer a path for anything but a small image.

## How a reference matches

Doc Detective always matches on both shape and color. What's in the reference decides how it compares them. All of these work in Chrome and Firefox.

**A transparent file in one color** matches its shape and its color on a background that's lighter or darker than the icon. A dark gray file finds a dark gray icon on a white page or a tinted toolbar. A white file finds a white icon on a dark toolbar. A red file doesn't find a blue icon with the same shape. It can miss an icon that stands out mainly by color rather than lightness, such as red on medium gray or green on magenta.

**A transparent file in several colors** matches its colors and shape on any background. A green check and a red cross in the same disc stay distinct, and a blue disc doesn't match a green one. It can miss an icon drawn with very thin lines, especially at small sizes.

A transparent file doesn't need to be the size it's displayed at. Doc Detective tries it at its own size, then at sizes from 12 to 64 pixels tall, and stops at the first near-perfect match. If there isn't one, the best match wins. A file in several colors is tried only at common icon sizes, such as 16, 24, and 32 pixels, so it can miss at others.

An SVG is rendered fresh at each size, so thin strokes stay sharp. A PNG is resized, so use one at least as tall as the icon is on the page.

**A reference with no transparency,** such as a crop from a screenshot, matches its colors and its background. An icon cropped from a white page won't match the same icon on a dark toolbar, or in a different color.

Doc Detective also tries it at the sizes it would have on screens at 100%, 125%, 150%, 175%, 200%, 225%, 250%, or 300% display scale. A crop of a graphic or a solid icon therefore works from a high-density screen on a standard one, and the other way round. A crop with thin lines or text can miss, especially on a screen with a higher density than the one it came from.

### Match an icon set's files

Most icon sets, such as Lucide, Feather, and Heroicons, draw in `currentColor`, which has no color until a page sets one. Doc Detective renders a file like that in black.

If the icon is another color on the page, give that color in `color`, as a six-digit hex value:

```json
{ "find": { "elementImage": { "path": "icons/save.svg", "color": "#1a5fb4" } } }
```

Use the color on screen. An icon with `opacity` looks lighter than the color its CSS names.

`color` works only with a transparent file in one color. With any other reference, the step fails and says so.

### How close a color has to be

At the default threshold, colors have to be close. Red doesn't match orange, and dark gray doesn't match medium gray. Close shades do match, such as two similar reds or two similar blues, because browsers don't draw colors identically. To tell close colors apart, raise `threshold`. On very thin lines, this can't separate a lighter shade from a darker one.

Browsers draw very thin lines lighter than their real color, so lightness counts for less on thin icons. A dark gray file can match a medium gray icon drawn with very thin lines. A red file still won't match a blue one.

## Use a match in other steps

Every field that accepts `elementText` also accepts `elementImage`.

[`click`](/docs/actions/click), and `click` inside `find`, press the center of the match. Every `button` value and `duration` work.

A `click` leaves the cursor on the icon. If the icon changes color on hover, a later `find` for it can fail, so move the cursor away first.

`moveTo` in `find` moves the cursor to the center of the match.

[`type`](/docs/actions/type) with `elementImage` clicks the center of the match, then types.

[`dragAndDrop`](/docs/actions/draganddrop) accepts `elementImage` on `source`, `target`, or both, and either end can use other criteria instead. The drag presses at the center of one end and releases at the center of the other, using pointer input only.

In Firefox, a drag by image can report success without dropping an element that uses HTML5 drag and drop. Confirm the drop with a `find` afterward, or use a `selector` at both ends.

[`screenshot`](/docs/actions/screenshot) `crop` with `elementImage` crops to the match plus any `padding`. It doesn't scroll first, because the match is already on screen.

A `crop` without `elementImage` scrolls its element into view, so a later `find` by image might not see what was on screen before it.

An [annotation](/docs/test-docs/annotate-screenshots) `target` with `elementImage` marks the first match. To mark every copy instead, such as to blur a logo everywhere it appears, add `all: true` to the annotation. When you're hiding something sensitive, check the result. A copy in another color or at an unusual size can stay visible while the step passes.

`find` in a `waitUntil` condition, on [`goTo`](/docs/actions/goto) and [`type`](/docs/actions/type), waits for the image to appear.

When you combine `elementImage` with other criteria, the match has to lie inside an element that meets them. Use this to choose between identical images:

```json
{ "find": { "selector": "#toolbar", "elementImage": "icons/save.svg" } }
```

## How matching decides

Doc Detective takes a screenshot of the surface and scores the reference at every location, for shape and for color. The lower of the two is the location's score, so a perfect shape in the wrong color still scores low. A score of 1 means a perfect match.

A location counts as a match when its score reaches `threshold`, which defaults to 0.9 and accepts values above 0, up to 1. Even at 1, a difference of a pixel or two can match, because an exact copy can score a hair under 1.

Matching sees only what's on screen, and it doesn't scroll. Scroll to the target first if it might be off screen.

`find` keeps looking until it finds a match or `timeout` runs out, which is 5000 milliseconds by default. With `timeout: 0`, it checks once.

It finishes any check it has started, so a step can run well past `timeout` on a large screen, sometimes by tens of seconds.

When several places match about equally well, the topmost wins, then the leftmost. This only compares copies at the same size. To choose between copies at different sizes, add a `selector`.

After a match, `outputs.element.location` and `outputs.element.size` describe the match in CSS pixels relative to the viewport, and `outputs.element.matchScore` holds its score. The other `outputs.element` fields are `null`, because a match has no DOM element behind it.

## Which references work across browsers

Icons and graphics work across browsers. Text is what doesn't, because each browser renders it differently. These results come from Chrome and Firefox on Windows, at the default threshold:

| Content                                                    | Across browsers |
| ---------------------------------------------------------- | --------------- |
| Icon files, solid or thin outline                          | Yes             |
| Icons cropped from a screenshot                            | Yes             |
| Canvas drawings, charts, gradients, and bitmaps            | Yes             |
| Text drawn in a canvas                                     | Yes             |
| Paragraphs, headings, and buttons with an icon and a label | Sometimes       |
| Buttons with text, and form inputs                         | No              |

A button with text has text you can target, so use `elementText` for it. To keep using an image, lower `threshold` for that step, or capture one per browser in tests gated with `runOn`.

## Tell near-identical images apart

Matching can miss small differences at the default threshold. A chart with one bar changed scored 0.94 against the original, so it passes when the original is gone. When the real target is on screen, it outranks the lookalike and wins.

To reject near-identical images, set a higher `threshold`:

```json
{ "find": { "elementImage": { "path": "chart.png", "threshold": 0.99 } } }
```

Graphics scored above 0.99 across browsers at the same display scale, so a high threshold doesn't stop them from matching there. A reference from a screen at another display scale can score lower and miss, so capture it at the scale your tests use.

Icons work the same way. An icon that differs from another of the same color by a small detail can pass when it's gone. For example, `square-check` scored up to 0.94 against `square`. If your test depends on that detail, such as whether a box is checked, set `threshold` to 0.97. This can miss thin icons, so check the match's score in `outputs.element.matchScore`.

An icon with a basic shape can also match text with the same shape and color. A `plus` icon scored up to 0.96 against a `+` in a paragraph, and `chevron-right` scored up to 0.95 against a `>`. To keep the search away from text, combine `elementImage` with a `selector` for the icon's container.

## When a match fails

A failed step names the place whose shape came closest, with its score, and says whether its shape or its color fell short. When only the color was wrong, it usually names both colors. When no part of the page could be compared, such as inside a `selector` smaller than the image, it says that instead.

A low shape score usually means that the reference has text rendered by another browser. It can also mean that a cropped reference's background changed, or that a multi-color file's colors changed. A low color score usually means that the page's color changed, or that a file drawn in `currentColor` needs `color`.

For an icon file, thin strokes score lower in these situations:

* The icon has a fractional size, such as `1.25em` of 14 pixels, or a `transform` moves it by part of a pixel. Lower `threshold` for that step to 0.8.
* The page overrides the icon's stroke width. Use a file with the same stroke width as the page.
* The file is a small PNG that was enlarged. Use an SVG, or a larger PNG.

A reference that's missing or isn't an image, including an invalid `base64` value, fails the step immediately, with no waiting.

A single-color reference with no transparency fails the step, because it would match any area of that color.

A reference too large to fit on screen, even at the smaller sizes Doc Detective tries, fails the step.

## Limits

`elementImage` works on browser surfaces only. On an [app surface](/docs/test-docs/native-windows-apps), the step fails and says so.

On a browser running on a mobile device, the step also fails and says so.