Load IMG in SVG DataURI

load crossOrigin IMG in SVG IMAGE, with mask applied

by WebComponents

HTML

<style>
  img {
    width: 40%;
    background: grey;
  }

</style>
<template>
  <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 50 50'>
    <mask id="circle">
      <circle cx='50%' cy='50%' r='20' fill="#fff" />
    </mask>
    <mask id="diamond">
      <polygon points="25 0 50 25 25 50 0 25" fill="#fff" stroke="#f00" stroke-width="4" />
    </mask>
    <image mask='url(#MASK)' x='0' y='0' width='50' height='50' href='IMG' />
  </svg>
</template>
<script>
  customElements.define('masked-img', class extends HTMLElement {
    static get observedAttributes() {
      return ["src", "mask"]; // update whenever these attributes change
    }
    connectedCallback() {
      this.hostIMG = this.appendChild(document.createElement("IMG"));
      this.onclick = (evt) => this.download();
      this.render();
    }
    attributeChangedCallback() {
    	this.render();
    }
    render(){
      let svg = document.querySelector("template").content.querySelector("svg");
      let img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = () => {
      	svg.setAttribute("width",img.width); // FF requires these?
      	svg.setAttribute("heigth",img.width);
        svg = svg.outerHTML;
        this.canvas = document.createElement("canvas");
        this.canvas.width = img.width;
        this.canvas.height = img.height;
        this.canvas.getContext("2d").drawImage(img, 0, 0);
        this.hostIMG.src = `data:image/svg+xml,` +
          svg.replace('IMG', this.canvas.toDataURL("image/png"))
          .replace('MASK', this.getAttribute("mask"))
          .replace(/"/g, "'")
          .replace(/#/g, "%23");
      };
      img.src = this.getAttribute("src"); //triggers onload
    }
    download() {
      //var dt = this.canvas.toDataURL('image/png'); // << this fails in IE/Edge...
      //dt = dt.replace(/^data:image\/[^;]*/, 'data:application/octet-stream');
      //dt = dt.replace(/^data:application\/octet-stream/,...