想要跟pchome一樣可以截圖,意外的google到這個元件,真好用
用html2canvas轉成canvas,再下載
載入js,js會把div裡的東西,轉換成canvas
<head>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
準備容器,把要截圖的內容,包在裡面(等等轉成canvas)
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
</div>
將canvas下載成jpg
<script>
function block_capture() {
html2canvas(document.querySelector("#capture")).then(function (canvas) {
a = document.createElement('a');//add canvas
a.href = canvas.toDataURL("image/jpeg", 0.92).replace("image/jpeg", "image/octet-stream");//toDataURL將canvas轉成base64
//下載成png toDataURL("image/png")
//下載成jpg toDataURL("image/jpeg")
a.download = 'image.jpg';
a.click();
});
}
</script>
全文
<!DOCTYPE html>
<html lang="zh-tw">
<head>
<meta charset=" UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<title>JavaScript canvas</title>
<style>
button{
margin: 5px;
}
</style>
</head>
<body>
<div id="capture" style="padding: 10px; background: #f5da55">
<h4 style="color: #000; ">Hello world!</h4>
<table><tr><td>3333</td></tr></table>
</div>
<button onclick="block_capture()">Click</button>
<script>
function block_capture() {
html2canvas(document.querySelector("#capture")).then(function (canvas) {
a = document.createElement('a');
a.href = canvas.toDataURL("image/jpeg", 0.92).replace("image/jpeg", "image/octet-stream");
a.download = 'image.jpg';
a.click();
});
}
</script>
</body>
</html>
ref
https://mnya.tw/cc/word/1573.html