其中 capture 爲要截取的 內容 (一個 class 或者一個ID 都可以)
down 爲存放 src 的圖片的 class
放大三倍 是爲了 圖片更加清晰
function img(){
//直接選擇要截圖的dom,就能截圖,但是因爲canvas的原因,生成的圖片模糊
html2canvas(document.querySelector('#capture')).then(function(canvas) {
document.body.appendChild(canvas);
})
//創建一個新的canvas
var canvas2 = document.createElement("canvas");
let _canvas = document.querySelector('#capture');
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//將canvas畫布放大若干倍,然後盛放在較小的容器內,就顯得不模糊了
canvas2.width = w * 3;
canvas2.height = h * 3;
canvas2.style.width = w*3 + "px";
canvas2.style.height = h*3 + "px";
//可以按照自己的需求,對context的參數修改,translate指的是偏移量
// var context = canvas.getContext("2d");
// context.translate(0,0);
var context = canvas2.getContext("2d");
context.scale(3,3);
html2canvas(document.querySelector('#capture'),{canvas:canvas2}).then(function(canvas) {
document.body.appendChild(canvas);
//canvas轉換成url,然後利用a標籤的download屬性,直接下載,繞過上傳服務器再下載
document.querySelector(".down").setAttribute('src',canvas.toDataURL());
});
}