How to build a JavaScript image viewer with Viewer.js

Table of contents

    How to build a JavaScript image viewer with Viewer.js
    TL;DR

    This tutorial shows how to build a JavaScript image viewer using Viewer.js, and compares it to Nutrient’s commercial viewer with annotations, multiformat support, and a polished UI.

    This post walks through building a JavaScript image viewer with the Viewer.js(opens in a new tab) library.

    The first part covers rendering and customizing an image viewer in the browser with Viewer.js. The second part shows how to build an image viewer with the Nutrient image viewer library. Our library provides some additional benefits, including:

    • A prebuilt UI
    • 15+ prebuilt annotation tools to enable document collaboration
    • Browser-based text editing, page cropping, merging, rotating, and more
    • Support for more file types with client-side PDF, MS Office, and image viewing
    • Dedicated support from engineers to speed up integration

    Viewer.js is a JavaScript image viewer library that renders images in a web browser. It supports zooming, rotating, and flipping images, along with keyboard shortcuts for navigation.

    Installing Viewer.js

    You can install Viewer.js as an npm package(opens in a new tab) or via a CDN from cdnjs(opens in a new tab).

    A CDN is a content delivery network or a server that hosts libraries, like Bootstrap.

    In this tutorial, you’ll use the CDN method. Copy the JavaScript and CSS files from the CDN(opens in a new tab).

    Create a blank index.html file and paste the following:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Viewer.js</title>
    <script
    src="https://cdnjs.cloudflare.com/ajax/libs/viewerjs/1.10.5/viewer.min.js"
    integrity="sha512-i5q29evO2Z4FHGCO+d5VLrwgre/l+vaud5qsVqQbPXvHmD9obORDrPIGFpP2+ep+HY+z41kAmVFRHqQAjSROmA=="
    crossorigin="anonymous"
    referrerpolicy="no-referrer"
    ></script>
    <link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/viewerjs/1.10.5/viewer.css"
    integrity="sha512-c7kgo7PyRiLnl7mPdTDaH0dUhJMpij4aXRMOHmXaFCu96jInpKc8sZ2U6lby3+mOpLSSlAndRtH6dIonO9qVEQ=="
    crossorigin="anonymous"
    referrerpolicy="no-referrer"
    />
    </head>
    </html>

    Creating the markup

    Now, create a container div for an image gallery and create a list for the images:

    <body>
    <div id="gallery">
    <ul class="images">
    <li>
    <img src="image-1.png" alt="blue background" />
    </li>
    <li>
    <img src="image-2.png" alt="gray background" />
    </li>
    <li>
    <img src="image-3.png" alt="black background" />
    </li>
    <li>
    <img src="image-4.png" alt="green background" />
    </li>
    <li>
    <img src="image-5.png" alt="red background" />
    </li>
    <li>
    <img src="image-6.jpeg" alt="pink background" />
    </li>
    </ul>
    </div>
    <script src="script.js"></script>
    </body>

    You can now interact with the viewer library. Create a script.js file and add the following code:

    const gallery = document.getElementById("gallery");
    const viewer = new Viewer(gallery);

    Here, you accessed the gallery container and created a new instance of the Viewer class, which enables you to start interacting with the viewer library.

    Serving the website locally

    Another option is to use the serve(opens in a new tab) package as a simple HTTP server. If you want to use that option, follow the steps below.

    1. Install the serve package:

      Terminal window
      npm install --global serve
    2. Serve the contents of the current directory:

      Terminal window
      serve -l 8080 .
    3. Navigate to http://localhost:8080 to view the website.

    Customizing the toolbar

    You can customize the toolbar by passing options to your viewer instance. You can view all the toolbar options in the Viewer.js documentation(opens in a new tab):

    const viewer = new Viewer(gallery, { options });

    For the custom toolbar, use the following options:

    const gallery = document.getElementById("gallery");
    const viewer = new Viewer(gallery, {
    // Custom toolbar.
    toolbar: {
    oneToOne: true,
    prev() {
    viewer.prev(true);
    },
    play: true,
    next() {
    viewer.next(true);
    },
    download() {
    const a = document.createElement("a");
    a.href = viewer.image.src;
    a.download = viewer.image.alt;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    },
    },
    });
    • Setting oneToOne to true shows the aspect ratio of the image.
    • The prev and next functions show the previous and next image.
    • The play function shows the image in fullscreen mode.
    • The download option helps you download the image.

    Nutrient JavaScript image viewer

    We offer a commercial JavaScript image viewer library that you can add to your web application. It renders JPEG, PNG, TIFF, and PDF files in any modern browser and on any mobile device without plugins.

    Example of our JavaScript image viewer

    To see our image viewer in action, upload a JPG, PNG, or TIFF file by selecting Choose Example > Standalone > Open Document. Once your image is displayed in the viewer, you can try drawing freehand, adding a note, or applying a crop or an eSignature.

    Requirements to get started

    Adding Nutrient to your project

    1. Install the @nutrient-sdk/viewer package from npm. If you prefer, you can also download the Nutrient Web SDK manually:

      Terminal window
      npm i @nutrient-sdk/viewer
    2. To make the Nutrient Web SDK work, copy the required library artifacts to your assets directory:

      Terminal window
      cp -R ./node_modules/@nutrient-sdk/viewer/dist/ ./assets/

    Make sure your assets folder includes:

    • nutrient-viewer.js
    • A nutrient-viewer-lib/ directory containing the runtime dependencies

    Integrating into your project

    1. Add the image you want to display to your project directory. You can use our demo image as an example.

    2. Add a <div> where the Nutrient viewer will be mounted:

      <div id="nutrient" style="height: 100vh;"></div>
    3. Include nutrient-viewer.js in your HTML:

      import "./assets/nutrient-viewer.js";
    4. Initialize the Nutrient viewer by calling NutrientViewer.load():

      <script type="module">
      import "./assets/nutrient-viewer.js";
      const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;
      NutrientViewer.load({
      container: "#nutrient",
      document: "image.png", // Path to your image.
      baseUrl,
      })
      .then((instance) => {
      console.log("Nutrient Viewer loaded", instance);
      })
      .catch((error) => {
      console.error(error.message);
      });
      </script>

    Example index.html file

    <!DOCTYPE html>
    <html>
    <head>
    <title>Nutrient Image Viewer</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    </head>
    <body>
    <div id="nutrient" style="height: 100vh;"></div>
    <script type="module">
    import "./assets/nutrient-viewer.js";
    const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;
    NutrientViewer.load({
    container: "#nutrient",
    document: "image.png",
    baseUrl,
    })
    .then((instance) => {
    console.log("Nutrient Viewer loaded", instance);
    })
    .catch((error) => {
    console.error(error.message);
    });
    </script>
    </body>
    </html>

    Nutrient image viewer displaying an image with toolbar and annotation options

    Adding even more capabilities

    Once you’ve deployed your viewer, you can customize it or add more features. Here are some of our most popular JavaScript guides:

    Conclusion

    In this article, you learned how to build an image viewer with Viewer.js, and then with Nutrient Web SDK. If you run into issues, contact our Support team.

    At Nutrient, we offer a commercial, customizable JavaScript image viewer library with well-documented APIs for advanced use cases. Try it for free, or visit our demo to see it in action.

    FAQ

    What is Viewer.js?

    Viewer.js is a JavaScript library for displaying and interacting with images in a web browser, offering features like zooming, rotating, and navigating images.

    How do I install Viewer.js?

    You can install Viewer.js using npm, or include it via a CDN.

    What are the steps to create an image viewer with Viewer.js?

    Install Viewer.js, set up your HTML structure, and initialize the viewer instance using JavaScript.

    Can I customize the toolbar in Viewer.js?

    Yes. You can customize the toolbar by passing options to the viewer instance when initializing it.

    What additional features does Nutrient offer over Viewer.js?

    Nutrient includes a prebuilt UI, annotation tools, and support for various file types.

    How do I integrate Nutrient into my project?

    Install Nutrient via npm, copy the necessary files, and initialize it using NutrientViewer.load() in your JavaScript.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Try for free Ready to get started?