Free tools Windows power users keep installed

One-click scans. No signup required.

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

Use PhantomJS’s page.evaluate() to find the element and return its getBoundingClientRect() values, assign that plain geometry object to page.clipRect, then call page.render(). PhantomJS will rasterize only that rectangle instead of the entire page.

Complete working example

This script captures the element matching #target from https://example.com/ and saves it as element.png.

var page = require('webpage').create();
page.viewportSize = { width: 1024, height: 768 };

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

  var rect = page.evaluate(function (selector) {
    var element = document.querySelector(selector);
    if (!element) return null;

    var bounds = element.getBoundingClientRect();
    return {
      top: bounds.top,
      left: bounds.left,
      width: bounds.width,
      height: bounds.height
    };
  }, '#target');

  if (!rect) {
    console.error('Target element not found');
    phantom.exit(1);
    return;
  }

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

Save it as capture.js and run it with the PhantomJS executable:

phantomjs capture.js

The result is an image containing the selected element’s rectangle. Change the selector, viewport, URL, and output filename for your page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How the workflow works

1. Set the viewport before loading

page.viewportSize controls the layout viewport used by the page. Responsive sites can render a different DOM, font flow, or component state at 1024×768 than at a phone-sized width. Set it before page.open(), and use the same dimensions whenever you need reproducible captures.

2. Check the load result

page.open() invokes its callback with a status value. Continue only when it is 'success'. A failed request, unreachable host, or other load error should terminate the script rather than produce a misleading image.

3. Select the element inside the page

page.evaluate() runs JavaScript in the page context, where normal DOM APIs and CSS selectors are available. Pass the selector as an argument, then call document.querySelector(selector). The first matching element is used; use a more specific selector when several nodes could match.

4. Return serializable geometry

Call getBoundingClientRect() and return only numeric properties such as top, left, width, and height. The boundary between PhantomJS and the page context cannot return a live DOM node, function, or closure as useful data. Returning a simple object avoids that problem.

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

5. Assign the clipping rectangle

page.clipRect defines the rectangle that page.render() rasterizes. Without a clipping rectangle, the render targets the whole page. Assign the object returned by evaluate() directly when the measured coordinates match the viewport coordinate system.

6. Render after the target is ready

Call page.render('element.png') only after the page has loaded and the target has its final dimensions. Then call phantom.exit() so the process ends with a useful exit status.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Choosing a selector and rectangle

CSS selector choices

  • #invoice-total is precise when the page gives the element a stable ID.
  • .product-card[data-sku="A123"] combines a class with an identifying attribute.
  • main article h1 is convenient but can break if the layout changes.

Prefer attributes or IDs that are part of the page’s stable markup. Avoid selectors based only on generated class names. If the target is inside an iframe, the top-level document cannot select it directly; the frame must be handled separately, and the supplied pattern does not provide an iframe traversal API.

One element or all matching elements

querySelector() returns one node. To capture a collection as one region, use querySelectorAll(), inspect each node’s rectangle, and calculate a union rectangle. That requires page-specific code because gaps, overlapping boxes, and off-screen items affect the desired result.

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

Zero-size and hidden elements

A hidden element can have zero width or height, or it can be present in the DOM before its content is inserted. Treat non-positive dimensions as a failure condition and report the selector. Capturing a zero-area rectangle cannot produce a useful screenshot.

Coordinate and layout pitfalls

Viewport-relative bounds

getBoundingClientRect() reports coordinates relative to the viewport. clipRect consumes the rectangle used by the renderer. The documented APIs do not define every edge case for scrolling, transforms, or page-specific coordinate behavior, so verify alignment on the actual output.

Scrolling

If the target is below the current viewport, its rectangle can have a negative top value or lie outside the visible area. Decide whether to scroll first, capture the currently visible portion, or use a page-specific strategy that moves the target into view before measuring. Re-measure after scrolling because the rectangle changes.

CSS transforms

Transforms can make the visual box differ from the element’s untransformed layout dimensions. If the result is offset or cropped, inspect the rendered image and compare it with the returned values. A wrapper around the transformed content may provide a more predictable capture region.

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.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Dynamic layout

Images, fonts, client-side data, consent dialogs, and animations can change the target after page.open() reports success. PhantomJS documentation demonstrates load-status handling but does not prescribe one universal wait rule for dynamic sites. Use a page-specific readiness condition, a controlled delay, or a callback that confirms the target’s content and dimensions before measuring.

Waiting for a dynamically populated element

A polling helper can wait for a selector and non-zero dimensions. The timeout and interval are examples; choose values appropriate for your page.

function waitForElement(page, selector, done, timeout) {
  var start = Date.now();
  var timer = setInterval(function () {
    var ready = page.evaluate(function (sel) {
      var el = document.querySelector(sel);
      if (!el) return false;
      var r = el.getBoundingClientRect();
      return r.width > 0 && r.height > 0;
    }, selector);

    if (ready) {
      clearInterval(timer);
      done(true);
    } else if (Date.now() - start > timeout) {
      clearInterval(timer);
      done(false);
    }
  }, 100);
}

waitForElement(page, '#target', function (ready) {
  if (!ready) {
    console.error('Target was not ready before timeout');
    phantom.exit(1);
    return;
  }
  // Measure, assign page.clipRect, render, and exit here.
}, 10000);

Keep the final measurement immediately before rendering. If an animation is still running, disable it with page-specific CSS or wait for a stable state; otherwise the same script can produce different crops on different runs.

Output formats and image quality

The PhantomJS capture guide documents PNG, JPEG, GIF, and PDF output. For a clipped DOM element, an image is normally the appropriate output. Use a filename extension that matches the format you intend to create. PNG preserves sharp text and transparency better for interface elements; JPEG can be smaller for photographic content but introduces compression artifacts. PhantomJS’s renderer and the page’s viewport determine the captured pixel dimensions, so confirm the output rather than assuming CSS pixels and image pixels are identical in every setup.

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

Manual rectangle versus DOM-derived rectangle

Approach How it works Best when Main risk
Manual coordinates Set page.clipRect to fixed top, left, width, and height values. The layout and viewport are fixed and known. Responsive changes or content shifts make the crop stale.
DOM-derived coordinates Select the element in evaluate(), return its bounds, and assign them to clipRect. The target can be selected reliably and its position changes with layout. Scroll state, transforms, or late layout changes can misalign the rectangle.

For a named element on a responsive page, DOM-derived coordinates are usually less brittle. For a pixel-perfect, fixed template, manual coordinates can be simpler and easier to audit.

Troubleshooting

“Target element not found”

Verify the URL, selector spelling, frame context, and timing. Log or inspect the page source if the element is inserted by client-side code. Do not assign null to clipRect; exit with an error and fix the readiness condition.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The image is blank or incomplete

Check the page.open() status, wait for dynamic content, and confirm that scripts and required resources are available. A successful navigation callback does not guarantee that application data has finished rendering.

The crop is shifted

Compare the viewport size, scroll position, and returned rectangle with the output. Re-measure after any scroll or layout change. Transforms and fixed-position elements may require a wrapper or a page-specific coordinate adjustment.

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

The crop is too small or empty

Inspect width and height before rendering. A collapsed, hidden, or not-yet-populated node may report zero dimensions. Wait until it is visible and non-zero.

Returning the element itself fails

Return plain JSON-compatible data instead. A DOM node is owned by the page context and is not a usable return value for this workflow.

Different runs produce different images

Stabilize the viewport, data, scroll position, fonts, image loading, and animation state. Capture only after the target’s bounds stop changing.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Operational and security considerations

PhantomJS is a legacy headless WebKit tool. The documentation used for this technique describes the API behavior but does not establish current maintenance or security-support status. Treat it as a compatibility choice for existing automation, not as evidence that it is suitable for a new production system. Run captures in an isolated environment, avoid exposing secrets in page scripts, and be cautious when loading untrusted URLs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Or skip the browser setup

If you need an element screenshot in a service rather than a local PhantomJS process, ScreenshotNeo accepts a URL and supports selecting one element with a CSS selector. It also offers full-page capture, 12 device presets plus custom viewports, retina scale, dark mode, custom CSS and JavaScript, waits, request blocking, cookies, headers, geolocation, timezone, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, bulk capture, PDF output, and an MCP server for AI clients.

Its HTTP response identifies whether the page was cleanly captured and billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot, with each cleanup step configurable.

One-call cURL example

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo documentation for selector and capture options. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. An MCP server lets Claude, Cursor, or another MCP client call screenshot tools directly. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Can PhantomJS capture an element by CSS selector in one built-in call?

No. The documented API clips a render to a rectangle. You select the element yourself, return its bounds, assign page.clipRect, and render.

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

Should I use document.body.scrollWidth for an element screenshot?

No. Use the target element’s rectangle. Page dimensions describe the document, not the selected node, and can create a crop that includes unrelated content.

What should I do when the target is inside an iframe?

The top-level document cannot query the iframe’s contents directly. Access the frame’s document with a page-specific approach, then measure the target in the correct browsing context and account for the frame’s position.

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.