如何在不使用像html2canvas这样的插件的情况下将以下内容绘制到画布上?
<div id="test">
asadasd <br />
fsdf<br />
sdfsd<br />
sdfsdfsdf<br />
</div>
<canvas id="myCanvas" width="150" height="150" style="border:1px solid #d3d3d3;"></canvas>
JS:
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("test");
ctx.drawImage(img,10,10);
}
答案 0 :(得分:1)
您不能将HTML作为变量发送到画布对象。这是非法的。实际上打印屏幕某人对页面的更改并将该图像发送到服务器并不容易。如果不动态动态(HTML&gt; var),您可以使用foreignObject
*Docs 。
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" id="test" style="font-size:16px; background:gold;">'+
'asadasd <br />' +
'fsdf<br />' +
'sdfsd<br />' +
'sdfsdfsdf<br />' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
<canvas id="myCanvas" width="150" height="150" style="border:1px solid #d3d3d3;"></canvas>