html2canvas

repository·master·Indexed 12 days ago

https://github.com/niklasvh/html2canvas

A JavaScript library that takes 'screenshots' of webpages or specific DOM elements by rendering the DOM and CSS into a canvas element. Version 1.4.1 supports client-side rendering in browsers including Chrome, Firefox, Safari, and IE9+, though it is not suitable for Node.js environments. It includes options for CORS handling via proxies, custom dimensions, and element exclusion using the data-html2canvas-ignore attribute.

Tokens
4.1K
Snippets
9
Records
22
Agent score
97%

What's inside html2canvas

  1. Use a proxy to support CORS content in html2canvas

    master

    By default, html2canvas cannot bypass browser content security policies. If you attempt to draw images from a different origin (domain) onto the canvas, the canvas becomes "tainted," which prevents you from reading its data (e.g., via toDataURL).

    To load cross-origin images and avoid canvas tainting, you must use a proxy to fetch the images on behalf of your application. This allows the images to be served from the same origin as your page, satisfying CORS requirements.

  2. Understand the limitations of html2canvas

    master

    When using html2canvas, be aware of the following constraints:

    • CSS Support: Only a subset of CSS properties are supported. If a property is not understood by the script, it won't be rendered.
    • Cross-Origin Images: Images must reside under the same origin as the script for html2canvas to read them. If images are cross-origin, you must use a proxy to avoid issues.
    • Tainted Canvases: If there are other canvas elements on the page that have been tainted with cross-origin content, they will become 'dirty' and html2canvas will no longer be able to read them.
    • Plugin Content: The script cannot render content from plugins such as Flash or Java applets.
  3. How html2canvas works

    master

    html2canvas renders a webpage or specific DOM elements as a <canvas> image by reading the DOM and the applied CSS styles.

    Key characteristics:

    • Client-side rendering: The entire image is created in the user's browser; no server-side rendering is required.
    • Not for Node.js: Because it relies heavily on browser APIs, it is not suitable for Node.js environments.
    • Cross-Origin Restrictions: It does not bypass browser content policies. To render cross-origin content, you must use a proxy to bring the content to the same origin.
    • Accuracy: Since it reconstructs the page based on DOM information rather than taking a literal pixel screenshot, the output may not be 100% accurate to the real representation.
  4. Exclude elements from rendering

    master

    There are two ways to prevent specific elements from appearing in the html2canvas output:

    1. HTML Attribute (Declarative): Add the data-html2canvas-ignore attribute to any element you wish to exclude.
    2. ignoreElements Option (Programmatic): Pass a predicate function to the ignoreElements option in the configuration object. This function receives the element as an argument and should return true if the element should be removed from the render.
    // Using the attribute
    // <div data-html2canvas-ignore>This will not be rendered</div>
    
    // Using the ignoreElements option
    html2canvas(document.body, {
      ignoreElements: (element) => {
        return element.classList.contains('no-render');
      }
    });
  5. Use html2canvas to render an element

    master

    To capture an HTML element as a canvas, import html2canvas and call the function passing the target element and an optional options object. The function returns a Promise that resolves to a canvas element.

    Basic usage pattern:

    1. Select the DOM element you want to capture.
    2. Call html2canvas(element, options).
    3. Use the resulting canvas (e.g., append it to the document).
    import html2canvas from 'html2canvas';
    
    html2canvas(document.body).then(function(canvas) {
        document.body.appendChild(canvas);
    });
  6. Build html2canvas from source

    master

    To build the browser bundle from the git repository, follow these steps:

    1. Clone the repository.
    2. Install dependencies using npm.
    3. Run the build script.

    Warning: The project is noted as being in a very experimental state.

    $ git clone git://github.com/niklasvh/html2canvas.git
    $ npm install
    $ npm run build
  7. Install the gatsby-starter-default starter

    master

    To create a new project using the gatsby-starter-default template, use the Gatsby CLI. Ensure you have Gatsby installed on your system before running the command.

    Run the following command from your terminal:

    gatsby new gatsby-example-site

    Note: gatsby-example-site is a placeholder for your desired project name.

  8. Configure html2canvas options

    master

    When calling html2canvas, you can pass an options object to customize the rendering process. Key configuration categories include:

    Canvas & Dimensions

    • backgroundColor: The canvas background color (default: #ffffff). Set to null for a transparent background.
    • scale: The scale factor for rendering (default: window.devicePixelRatio).
    • width / height: The dimensions of the resulting canvas.
    • x / y: The x and y coordinates used to crop the canvas.
    • canvas: An existing canvas element to use as the base for drawing.

    Image & Cross-Origin Handling

    • useCORS: Whether to attempt to load images from a server using CORS (default: false).
    • allowTaint: Whether to allow cross-origin images to taint the canvas (default: false).
    • proxy: A URL to a proxy server used for loading cross-origin images. If left empty, cross-origin images will not be loaded.
    • imageTimeout: Timeout for loading an image in milliseconds (default: 15000). Set to 0 to disable.

    Rendering Environment

    • windowWidth / windowHeight: The window dimensions to use during rendering, which can affect media queries.
    • scrollX / scrollY: The scroll position used when rendering elements (useful for position: fixed elements).
    • foreignObjectRendering: Whether to use ForeignObject rendering if supported by the browser.

    Lifecycle & Debugging

    • onclone: A callback function triggered after the document has been cloned. Use this to modify the cloned document's contents before rendering without affecting the original DOM.
    • ignoreElements: A predicate function (element) => boolean to remove specific elements from the render.
    • logging: Enables logging for debugging purposes (default: true).
    • removeContainer: Whether to clean up the temporary cloned DOM elements (default: true).
  9. Handle incomplete CSS property rendering

    master
    html2canvas does not have full CSS support because every property must be manually implemented. It only supports the most commonly used CSS properties. If a specific property is not rendering correctly, it is likely not yet implemented in the library.
  10. Resolve missing images due to CORS or Tainting

    master

    html2canvas cannot bypass browser content policy restrictions. Drawing images from a different origin than your page will 'taint' the canvas, making it unreadable.

    To resolve this:

    1. Check allowTaint configuration: If allowTaint is set to false, html2canvas will skip images that would taint the canvas.
    2. Use a Proxy: To load images from outside your page's origin without tainting the canvas, you must use a proxy.
  11. Fix empty or cut-off canvases by adjusting window size

    master

    If your produced canvas is empty or cut off, you may be hitting browser-specific canvas size limitations. You can mitigate this by using the windowWidth and windowHeight configuration options to set a custom window size that matches the dimensions of the element you are capturing.

    await html2canvas(element, {
        windowWidth: element.scrollWidth,
        windowHeight: element.scrollHeight
    });