Take an element screenshot
Capture a single element with a locator screenshot instead of cropping a full-page image.
To capture one element, a card, a chart, a toolbar, call screenshot() on its locator. It writes just that element's box, not the whole page, so you skip cropping and the image stays stable when unrelated parts of the layout move.
Capture the element to a file
Build a locator for the element and pass a path. The file is written to disk and the method returns null when a path is given.
$context = Playwright::chromium();
$page = $context->newPage();
$page->goto('https://app.example.test/reports');
$page->getByRole('figure', ['name' => 'Revenue chart'])->screenshot('chart.png');
The locator resolves one element. If it matches several, the call fails on the ambiguity, so narrow it with a role name or a test id first.
Set options with an array
Screenshot options go in an array as the second argument. Use type for the format, and mask to hide elements you do not want in the image, such as a live timestamp.
$page->getByTestId('invoice')->screenshot('invoice.png', [
'type' => 'png',
'mask' => [$page->getByTestId('generated-at')],
]);
The off-screen element trap
You do not need to scroll first. screenshot() scrolls the element into view before it captures, so an element below the fold still works. What it will not do is capture something that never becomes visible: a locator on a hidden or zero-size element waits for it to be actionable, then times out. Make the element visible, expand its container, open the panel, before you capture.
Expected result
The artifact contains only the element's box. Use it as evidence or a visual baseline, but keep a locator assertion near it when the test must prove behavior.