iam-medvedev / eyedropper-polyfill

EyeDropper API Polyfill
https://www.npmjs.com/package/eyedropper-polyfill
MIT License
14 stars 1 forks source link

Load in browser via `script` tag? #2

Closed BigglesZX closed 2 months ago

BigglesZX commented 2 months ago

Thanks for your work on this polyfill! I'm attempting to add EyeDropper functionality to a custom input field in Craft CMS. I wondered if it's possible to load the polyfill directly in the browser via a script tag? I guess I would need to build it locally first? I appreciate that this is probably not a common use-case but any pointers would be much appreciated.

iam-medvedev commented 2 months ago

Sure!

You can use this:

<script type="module" src="https://esm.sh/eyedropper-polyfill@latest"></script>

Example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>eyedropper-polyfill demo</title>
    <style>
      body {
        height: 5000px;
      }

      button {
        position: fixed;
        top: 0;
        right: 0px;
      }
    </style>
  </head>

  <body>
    <button id="eyedropper">Get color</button>

    <div id="result"></div>
    <br />
    <br />

    <img src="https://picsum.photos/id/1/200/300" />
    <img src="https://picsum.photos/id/235/200/300" />
    <img src="https://picsum.photos/id/237/200/300" />
    <img src="https://picsum.photos/id/238/200/300" />

    <script type="module" src="https://esm.sh/eyedropper-polyfill@latest"></script>
    <script>
      const eyeDropperBtn = document.getElementById("eyedropper");
      const resultPreview = document.getElementById("result");

      const eyeDropperInstance = new window.EyeDropper();

      eyeDropperBtn.onclick = async () => {
        const result = await eyeDropperInstance.open();
        const color = result.sRGBHex;
        resultPreview.style.background = color;
        resultPreview.innerText = color;
      };
    </script>
  </body>
</html>
BigglesZX commented 2 months ago

Brilliant, thank you. I had forgotten about script type="module" :)