js实现HTML转换成图片
程序员文章站
2022-04-09 08:55:07
...
1.首先利用html2canvas把html转换成canvas
html2canvas($('#content'),{
onrendered: function(canvas) {
document.body.appendChild(canvas);
}
})
2.利用canvas对象方法:toDataURL()把canvas转换成图片
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
得到的数据格式为:data:image/png;base64…
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.min.js"></script>
<script src="html2canvas.js"></script>
</head>
<body>
<div id="content" style="width:150px;height:150px;border:1px solid blue;">
<span>Hello World!</span>
<br>
<span><h2>Are you hear me?</h2></span>
</div>
<button id="btnSave">save</button>
<script>
$(function(){
$('#btnSave').click(function(event) {
html2canvas($('#content'),{
onrendered: function(canvas) {
document.body.appendChild(canvas);
convertCanvasToImage(canvas);
}
})
});
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
document.body.appendChild(image);
return image;
}
})
</script>
</body>
</html>
上一篇: io流的简单应用1