前端截图 前端生成海报 下载
2022-07-08 本文已影响0人
银角大王__
- 截取内容为div
- 通过html2canvas截取 生成Bob | base64
- 保存图片到本地(无法下载的生成图片,长按图片保存到本地)
- style
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.view {
width: 375px;
height: 667px;
position: relative;
color: #FFFFFF;
text-align: center;
font-size: 20px;
background: #409EFF;
}
.title {
width: 100%;
font-size: 30px;
position: absolute;
top: 50px;
left: 50%;
transform: translateX(-50%);
}
.content {
width: 100%;
font-size: 16px;
position: absolute;
top: 100px;
left: 50%;
transform: translateX(-50%);
}
.result {
width: 375px;
height: 667px;
}
.result>img {
width: 100%;
height: 100%;
}
.btn {
padding: 10px;
}
button {
padding: 6px 10px;
}
</style>
- html
<div class="btn">
<button onclick="saveFile()">保存海报</button>
<button onclick="drawImage()">生成图片</button>
</div>
<div id="capture" class="view">
<div class="title">海报标题</div>
<div class="content">海报内容</div>
</div>
<br>
<hr>
<div id="result" class="result"></div>
- js
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.4.1/html2canvas.js"></script>
<script>
function saveFile() {
let dpi = window.devicePixelRatio || 2
let options = {
useCORS: true,
ignoreElements: false,
scale: dpi //设置默认值 提高图片分辨率
};
html2canvas(document.querySelector("#capture"), options).then(canvas => {
// document.body.appendChild(canvas)
canvas.toBlob(function (blob) {
downloadBob(blob);
});
});
}
function drawImage() {
let dpi = window.devicePixelRatio || 2
let options = {
useCORS: true,
ignoreElements: false,
scale: dpi //设置默认值 提高图片分辨率
};
html2canvas(document.querySelector("#capture"), options).then(canvas => {
let url = canvas.toDataURL('image/png') //base64
document.querySelector('#result').innerHTML = `<img src="${url}" alt="海报" />`
});
}
// 下载不了的 生成图片长按保存
function downloadBob(blob) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = '海报.png';
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
</script>