前端截图 前端生成海报 保留图片
- 内容为 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;}
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> 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); }