Home > Software design >  IMG elements can be dragged from web pages to other applications. How can I implement this for dynam
IMG elements can be dragged from web pages to other applications. How can I implement this for dynam

Time:11-19

As stated in the question, you can drag an IMG element from a web page into any other application that accepts it. You can also right-click to select "Save Image As...".

Is there a way to make this work with images (which are dynamically generated)? I had some luck converting the SVGs to data urls and passing them to IMG tags, but this doesn't seem to work on all browsers and is cumbersome.

EDIT: the one answer lead me to consider using Blobs and URL.createObjectURL(). Not sure if this would be less brittle than data urls.

CodePudding user response:

By saving the content in a separate file, and adding it into your webpage as the source of an img element:

<img src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/410.svg" />

EDIT: Converting an SVG to a data URL is probably the best way to go. Here are some of data URI's advantages/disadvantages, and here is the official caniuse page for data URIs. I'm not sure what you mean by "this doesn't seem to work on all browsers". Perhaps your encoded image (plus the encoding scheme text) is larger than 32kB (the maximum length of data URIs)?

CodePudding user response:

You can leave the heavy lifting to a native JavaScript Web Component, supported in all modern browsers:

  • load the external SVG as text
  • post process SVG to encode for a DataURI
  • create <img>
  • set DataURI as src
  • !! replace the Web Component itself with the <img>

<style>
  img { height:140px }
</style>

<svg-to-img src="//svg-cdn.github.io/heart.svg"></svg-to-img>
<svg-to-img src="//svg-cdn.github.io/joker-card.svg"></svg-to-img>
<svg-to-img src="//svg-cdn.github.io/svg_circle_spinner.svg"></svg-to-img>

<script>
  customElements.define("svg-to-img", class extends HTMLElement {
    async connectedCallback() {
      let src = this.getAttribute("src");
      let options = { /* fix potential CORS issues, client AND server side */ };
      let svg = await (await fetch(src,options)).text();
      let img = Object.assign(document.createElement("img"), {
        src: "data:image/svg xml,"   svg.replace(/"/g, "'").replace(/#/g, '#'),
        onl oad: (e) => console.log("Loaded SVG as IMG", src),
        one rror: (e) => console.error(e)
      });
      this.replaceWith(img);
    }
  })
</script>

Note: Where Browsers accept SVGs without NameSpace; for DataURIs xmlns="http://www.w3.org/2000/svg" is vital on your SVG!

  • Related