頁面生成圖片-html2canvas
阿新 • • 發佈:2019-01-03
頁面生成圖片-html2canvas
引入js
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
html2canvas詳細參考官方:http://html2canvas.hertzen.com/
示例
編寫html,指定根標籤id:table
<table id="table" border="1px" style="height: 100px;width: 100px;background-color: #CCCCCC;" align="center"> <tr> <td>1</td> <td>1</td> <td>1</td> </tr> <tr> <td>2</td> <td>2</td> <td>2</td> </tr> </table>
生成圖片base64
$("#bun").click(function() {
html2canvas(document.querySelector("#table")).then(function(canvas) {
var imgUri = canvas.toDataURL();
console.log(imgUri); //圖片:base64字串
$("body").append('<a href="' + imgUri + '" download="'+Date.parse(new Date())+'">下載圖片</a>');
})
})
備註:測試下載圖片,可使用Firefox 和 Chrome瀏覽器
base64轉File物件
function base64URLtoFile(base64Url, filename) {
var arr = base64Url.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {
type: mime
});
}
base64圖片上傳
function fileupload(base64Url) {
var form = document.forms[0];
var formData = new FormData();
formData.append("file", base64URLtoFile(base64Url, Date.parse(new Date()) + ".png"));
$.ajax({
url: '/file/upload',
type: 'POST',
data: formData,
dataType: 'json',
async: true,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(data) {
alert(data);
}
});
}