使用html2canvas根截取网页某dom部分为图片并缩小图片。
$('body').on('click', '#saveToImgBtn', function () { $.getScript('./style_1/html2canvas.min.js', function () { html2canvas(document.querySelector("#numberTable")).then(canvas => { //声明一个新的画板,用于生成新的缩小的图片,缩小倍数为 3 var new_canvas = document.createElement("canvas"), times = 3; new_canvas.setAttribute('width', canvas.width / times); new_canvas.setAttribute('height', canvas.height / times); var ctx = new_canvas.getContext('2d'); ctx.drawImage(canvas, 0, 0, canvas.width / times, canvas.height / times); //即时下载链接,这种形式的链接在pc端可以,手机上不行 var a = document.createElement('a'), day = new Date(); a.target = '_blank'; //下面代码中如果直接使用canvas,则是原图 a.href = URL.createObjectURL(convertToBlob(new_canvas.toDataURL("image/png", 1))); a.download = '选号 ' + day.getFullYear() + '-' + (parseInt(day.getMonth()) + 1) + '-' + day.getDate() + '.png';//下载文件名 $(a).text("下载").hide(); $("body").append(a); a.click();//触发下载 }); }); }); function convertToBlob(_base64) { var byteString = atob(_base64.split(',')[1]), mimeString = _base64.split(',')[0].split(':')[1].split(';')[0], ab = new ArrayBuffer(byteString.length), ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i) } return new Blob([ab], { type: mimeString }) }