- 截取內(nèi)容為div
- 通過html2canvas截取 生成Bob | base64
- 保存圖片到本地(無法下載的生成圖片,長按圖片保存到本地)
<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>
<div class="btn">
<button onclick="saveFile()">保存海報(bào)</button>
<button onclick="drawImage()">生成圖片</button>
</div>
<div id="capture" class="view">
<div class="title">海報(bào)標(biāo)題</div>
<div class="content">海報(bào)內(nèi)容</div>
</div>
<br>
<hr>
<div id="result" class="result"></div>
<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 //設(shè)置默認(rèn)值 提高圖片分辨率
};
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 //設(shè)置默認(rèn)值 提高圖片分辨率
};
html2canvas(document.querySelector("#capture"), options).then(canvas => {
let url = canvas.toDataURL('image/png') //base64
document.querySelector('#result').innerHTML = `<img src="${url}" alt="海報(bào)" />`
});
}
// 下載不了的 生成圖片長按保存
function downloadBob(blob) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = '海報(bào).png';
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
</script>