What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To capture one element in PhantomJS, measure its DOM rectangle with getBoundingClientRect(), convert the coordinates to page coordinates when the page is scrolled, assign the result to page.clipRect, then call page.render(). The example below is intended for maintaining existing PhantomJS scripts: upstream development is suspended, and the repository has been read-only since May 30, 2023.

Crop an element with clipRect

PhantomJS does not take a screenshot by CSS selector directly. Instead, its documented page.clipRect property accepts a rectangle with top, left, width, and height. That rectangle defines the area rasterized when page.render() runs. The practical steps are: find the element in the page context, return its measured dimensions to the PhantomJS script, set the clipping rectangle, and render.

Save this as element-shot.js and run it with the PhantomJS binary already installed in your environment. Replace the example URL and selector with your own.

var page = require('webpage').create();

// Choose the viewport before navigation if responsive CSS matters.
page.viewportSize = { width: 1280, height: 900 };

page.open('https://example.com/', function (status) {
  if (status !== 'success') {
    console.log('Unable to load the page');
    phantom.exit(1);
    return;
  }

  // Return only plain numeric values from the page context.
  var rect = page.evaluate(function (selector) {
    var element = document.querySelector(selector);
    if (!element) {
      return null;
    }

    var box = element.getBoundingClientRect();
    return {
      top: box.top + window.pageYOffset,
      left: box.left + window.pageXOffset,
      width: box.width,
      height: box.height
    };
  }, '#target');

  if (!rect || rect.width <= 0 || rect.height <= 0) {
    console.log('Target element not found or has no visible dimensions');
    phantom.exit(1);
    return;
  }

  page.clipRect = rect;
  page.render('element.png');
  phantom.exit();
});

The coordinate conversion is important. getBoundingClientRect() reports a box relative to the visible viewport; adding pageYOffset and pageXOffset converts its top and left to page coordinates. This is an implementation recipe based on the page evaluation and clipping APIs, not a canonical element-cropping snippet published by PhantomJS. Check the result in the PhantomJS build you use, especially when the page is scrolled or the element is positioned unusually.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

What each part of the script does

Set the viewport before opening the page

page.viewportSize controls the viewport used for layout. Set both width and height before page.open() if the desired crop depends on responsive breakpoints, viewport-relative units, or other window-size-dependent CSS. A different viewport can change the element’s position and dimensions, so measure only after the page has loaded at the intended size.

Measure inside page.evaluate()

page.evaluate() executes code in the page context. Its arguments and return values must be simple JSON-serializable values. Return a plain object containing numbers, as above; do not try to return the DOM node itself or pass a page-context closure back into the PhantomJS script. A missing selector returns null so the caller can stop cleanly rather than rendering an invalid crop.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Assign the rectangle and render

Set page.clipRect before calling page.render(). The rectangle has four numeric fields: top, left, width, and height. Without a clipping rectangle, rendering processes the full page; with it, rendering rasterizes the specified rectangular area. The dimensions here come from the element’s bounding box, so the crop includes the box rather than only its text or visible pixels.

Wait for the right page state before measuring

A successful page.open() callback is a starting point, not proof that a client-side application has finished updating. If JavaScript inserts the target later, or images and fonts alter its layout, measuring immediately can produce a missing element, stale coordinates, or a crop of the wrong size. Wait for the actual condition your page needs, then measure and render.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
  • For a target inserted asynchronously: poll for the selector or use a known application-ready signal before running the measurement.
  • For a page with delayed visual changes: wait for the relevant content or image to settle. A fixed delay can help with a known page but does not guarantee readiness on every load.
  • For layout-sensitive captures: measure after the final viewport and page state are established; changing either after measurement can invalidate the rectangle.
  • For debugging: log the returned rectangle and inspect whether its dimensions and position are plausible before rendering.

PhantomJS’s official viewport example demonstrates waiting briefly before rendering, but a delay is only an example, not a universal synchronization method. Prefer a condition tied to the content you need whenever the page provides one.

Handle crop boundaries and unusual layouts

Missing or zero-size elements

querySelector() returns no element if the selector does not match. An element can also exist but report a width or height of zero, for example if it is not laid out. The example checks both cases and exits with a nonzero status. If that happens, verify the selector, whether the element is hidden, and whether measurement occurs after it is created and displayed.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Scrolled pages and off-screen targets

The example adds the current scroll offsets because the bounding box is viewport-relative while clipping is configured on the page. Validate that conversion on the target page and PhantomJS build. If the element is partly outside the page or viewport, clipping may capture only the intersecting region or behave differently than expected; test the output rather than assuming the requested rectangle will extend the rendered page.

Transforms and nested frames

CSS transforms can make the visual shape differ from the simple untransformed layout box a developer expects. The bounding rectangle is still a rectangle, not a pixel-perfect outline around a rotated or irregular element. Similarly, an element inside an iframe must be located in the relevant frame context; the top-level document’s querySelector() will not find it. Treat these as page-specific cases and inspect the measured values in the runtime you have.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose an output format

page.render() selects the format from the output filename extension. The documented formats include PDF, PNG, JPEG, BMP, and PPM; GIF support depends on the Qt build. For a UI crop, PNG preserves sharp text and edges without lossy compression. JPEG can make a smaller lossy image when that trade-off is acceptable. Neither format is universally best; choose based on the downstream use. The example writes element.png.

Troubleshoot common failures

Symptom Likely cause What to check or change
“Unable to load the page” page.open() did not complete successfully. Confirm the URL is reachable from the machine running PhantomJS and inspect network or runtime compatibility issues before measuring.
Target not found The selector is wrong, the element is in another frame, or it has not been inserted yet. Check the selector in the page, account for iframe context, and wait for the target’s readiness condition.
Zero-sized crop The matched element has no laid-out dimensions at measurement time. Check whether it is hidden or not yet populated; measure only after the intended display state is reached.
Crop is shifted after scrolling Viewport-relative coordinates were used as though they were page-relative, or the runtime handles a special layout differently. Include scroll offsets as shown, log the measured rectangle, and validate the result in the installed PhantomJS build.
Crop cuts off content or looks stale The box was measured before a layout change, image load, or asynchronous update. Wait for the relevant page state before measuring; do not rely on load completion alone when the application continues rendering.
Unexpected output type The filename extension selects a different render format, or a format depends on the Qt build. Use a supported extension such as .png or .jpg; treat GIF as build-dependent.

Legacy status and practical reliability

PhantomJS is a legacy environment, not a current recommendation for a new browser-automation project. The upstream ariya/phantomjs repository says development is suspended until further notice, was archived read-only on May 30, 2023, and identifies 2.1 as the latest stable release. For a script you must maintain, verify the installed binary, operating-system compatibility, and actual page behavior. A recipe that works in one old runtime should not be assumed to behave identically across environments.

For repeatable output, keep the viewport fixed, wait for page-specific readiness, validate the rectangle, and retain a representative output image for regression checks. PhantomJS does not make timing, network behavior, or modern-site compatibility uniform; the capture depends on the page and the installed runtime.

Or skip the browser setup

If the goal is a website capture rather than preserving a PhantomJS script, ScreenshotNeo is a website screenshot API and MCP server. It can capture clean PNG, JPEG, WebP, or PDF output, including a single element by CSS selector. Here is the one-request cURL example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Before a capture, it can accept cookie or consent banners like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

The free plan includes 1,000 screenshots per month with no card required; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo and start with 1,000 free screenshots a month, no card required.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.