Skip to content Skip to sidebar Skip to footer

Html Content On Canvas

How to append html content on canvas.I tried but not working. any way is there to append html on canvas. http://jsfiddle.net/mktgnp3e/780/ var c = document.getElementById('myCanvas

Solution 1:

The basic idea is to copy the HTML + the styles for the HTML to a <foreignObject>inside an SVG element. Then you take a screenshot of the SVG element and draw it on the canvas using drawImage. There are lots of problems especially if you want to use images, since tainted canvases may not be exported. Next come some code but I wouldn't advise to use it in production.

letHTMLcontent = document.querySelector("#content");
let w = 340,h = 240;

(functioncopyCSS(){
  let styles0 = document.querySelectorAll("style")[0]
  let oldStyle = styles0.textContent;
  let newStyle = document.createElement("style");
  newStyle.textContent = oldStyle;
  styles0.parentNode.removeChild(styles0);
  HTMLcontent.prepend(newStyle);
})();

// SVG need well formed XHTMLHTMLcontent.setAttribute("xmlns", "http://www.w3.org/1999/xhtml"); 
let xml = newXMLSerializer().serializeToString(HTMLcontent);


let data = `<svg xmlns= 'http://www.w3.org/2000/svg' width='${w}' height='${h}'>
           <foreignObject width='100%' height='100%' >`+
       
            xml+
    
           `
           </foreignObject>
           </svg>`;



button.addEventListener("click",function(){

 
let img = newImage();
let svg = newBlob([data], {type: 'image/svg+xml'});
let url = URL.createObjectURL(svg);
img.src = url;
img.onload = function() {
  

let canvas = document.createElement('canvas');
canvas.width = w; 
canvas.height = h;
canvas.getContext('2d').drawImage(this, 0, 0,this.naturalWidth,this.naturalHeight);
  document.body.prepend(canvas);


  URL.revokeObjectURL(url); 
}

});
canvas{background:#333;}
html {
  font-size: 16px;
 
}
#content{
  width:250px;
  background-color: #e9e9e9;
  border:1px solid #d9d9d9;
  padding:1em;
  margin:1em;
  border-radius:10px;
}
h1 {
  color: #333;
  font-size: 1.5em;
  font-weight: bold;
  text-align: center;
  max-width: calc(5 * 16rem);
  margin: 1em auto;
  border-bottom: 1px solid #d9d9d9;
}

 p {
  font-size: .8rem;
  line-height: 150%;
  text-align:center;
}
<divid="content"><h1>How to append html content on canvas</h1><p>I tried but not working. Any way is there to append html on canvas?</h1></div><buttonid="button"style="margin: .5em;">Get screenshot</button>

Please click the button do get the screenshot. A canvas (dark background #333) element will be prepended to the body.

Post a Comment for "Html Content On Canvas"