画布上的HTML内容

时间:2018-09-05 11:11:56

标签: html html5 html5-canvas

如何在画布上附加html内容。我试过但不起作用。有任何方法可以将html附加到画布上。

http://jsfiddle.net/mktgnp3e/780/

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

 var html="<span><p>Content....</p></span>";

ctx.font = "20px Georgia";
ctx.fillText("Hello World!", 10, 50); 
ctx.font = "30px Verdana"; 
 var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
 gradient.addColorStop("1.0", "red");
 // Fill with gradient
 ctx.fillStyle = gradient;  
 ctx.fillText(html, 10, 90);

1 个答案:

答案 0 :(得分:1)

基本思想是将HTML + HTML的样式复制到SVG元素内部的<foreignObject>中。然后,获取SVG元素的屏幕截图,并使用drawImage将其绘制在画布上。有很多问题,尤其是如果您要使用图像,因为可能无法导出受污染的画布。接下来是一些代码,但是我不建议在生产中使用它。

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

(function copyCSS(){
  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 XHTML
HTMLcontent.setAttribute("xmlns", "http://www.w3.org/1999/xhtml"); 
let xml = new XMLSerializer().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 = new Image();
let svg = new Blob([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;
}
<div id="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>

<button id="button" style="margin: .5em;">Get screenshot</button>

请单击按钮以获取屏幕截图。画布(深色背景#333)元素将添加到正文中。