Rayrun

How do I take a screenshot with a transparent background using Playwright?

Answer

Taking Transparent Screenshots with Playwright

You can capture PNG images with transparent backgrounds using Playwright. To do this, set the omitBackground property to true when taking a screenshot. This hides the default white background and allows for transparency. Here's how you do it:

import { test } from '@playwright/test';

test('take screenshot with transparent background', async ({ page }) => {
  await page.goto('https://ray.run/');
  await page.screenshot({ path: 'screenshot.png', omitBackground: true });
});

Remember, this doesn't work for JPEG images.

Customizing Image Type and Quality

Playwright lets you specify the image type and quality using the type and quality properties. By default, the type is PNG. The quality is a scale of 0-100, but it doesn't apply to PNG images.

Scaling Your Screenshot

You can also scale your screenshot based on CSS or device pixels using the scale property. If you set it to "css", screenshots will have a single pixel per each CSS pixel. For high-dpi devices, this keeps screenshots small. If you set it to "device", screenshots will have a single pixel per each device pixel, making screenshots of high-dpi devices larger.

Playwright offers a variety of options for taking screenshots with transparent backgrounds in PNG format. You can customize the scaling and quality to suit your needs.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.