H5转图片支持保存

时间:2023-03-09 13:30:43
H5转图片支持保存
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>html2img</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
position: relative;
}
.s_html {
width: 100%;
position: relative;
}
.s_html img {
display: block;
}
.msg_1 , .msg_2 {
position: absolute;
width: 100%;
box-sizing: border-box;
height: 60px;
line-height: 60px;
text-align: center;
left: 0;
}
.msg_1 {
bottom: 120px;
padding: 20px;
}
.msg_1 div{
background: red;
width: 100%;
}
.msg_2 {
bottom: 188px;
padding: 20px;
}
.msg_2 div {
background: blue;
width: 100%;
}
.down {
position: absolute;
bottom: 80px;
right: 20px;
z-index: 1;
padding: 10px 20px;
border-radius: 10px;
background: rgba(0, 0, 0, .6); }
</style>
</head>
<body>
<div id="s_html" class="s_html">
<!-- <a class="down" href="" download="downImg">下载</a> -->
<img width="100%" src="./img/1212.jpg" alt="bg">
<div class="msg_1" id="msg_1">
<div>
lpl <span>总冠军</span>
</div> </div>
<div class="msg_2" id="msg_2">
<div>
IG <span>牛逼</span>
</div> </div>
</div>
<!-- <a class="down" id="down" href="" download="downImg">下载</a> -->
</body>
<script src="./js/jquery-3.3.1.js"></script>
<script src="./js/html2canvas.min.js"></script>
<script src="./js/canvas2image.js"></script>
<script>
// 获取jq转化为dom对象
var s_html = $('#s_html').get(0);
// 将html转化成canvas
html2canvas(s_html).then(function(canvas) {
// canvas宽度
var canvasWidth = canvas.width;
// canvas高度
var canvasHeight = canvas.height;
// 清空body
$('#s_html').html('');
// 渲染canvas
$('#s_html').append(canvas);
// 调用Canvas2Image插件
var img = Canvas2Image.convertToImage(canvas, canvasWidth, canvasHeight);
// 清空body
$('#s_html').html('');
// 显然img
$('#s_html').append(img);
$(img).css({
"width": $('#s_html').width() + "px",
"height": 'auto',
"-webkit-touch-callout":"default"
})
})
</script>
</html>

地址https://github.com/TankRyze/html2img