將網(wǎng)頁(yè)保存為圖片(canvas生成的圖片)

最近發(fā)現(xiàn)項(xiàng)目中需要點(diǎn)擊按鈕保存頁(yè)面為圖片,就是網(wǎng)頁(yè)截屏,通過用戶自主填寫或是答案生成圖片然后發(fā)朋友圈或是其他的圈。

而html2canvas?能幫助前端實(shí)現(xiàn)這一功能:

<script src="../../js/jquery-3.4.1.min.js"></script>

<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>

<p>我的邀請(qǐng)碼</p>

<p>我的邀請(qǐng)碼</p>

<p>我的邀請(qǐng)碼</p>

<p class="erweima"><a class="down" href="" download="downImg">保存二維碼</a></p>

<script>

? //直接選擇要截圖的dom,就能截圖,但是因?yàn)閏anvas的原因,生成的圖片模糊

? //html2canvas(document.querySelector('div')).then(function(canvas) {

? // document.body.appendChild(canvas);

? //});

? //創(chuàng)建一個(gè)新的canvas

? var canvas2 = document.createElement("canvas");

? let _canvas = document.querySelector('html');

? //此處可換body,或div等

? var w = parseInt(window.getComputedStyle(_canvas).width);

? var h = parseInt(window.getComputedStyle(_canvas).height);

? //將canvas畫布放大若干倍,然后盛放在較小的容器內(nèi),就顯得不模糊了

? canvas2.width = w;

? canvas2.height = h;

? canvas2.style.width = w + "px";

? canvas2.style.height = h + "px";


? //可以按照自己的需求,對(duì)context的參數(shù)修改,translate指的是偏移量

? // var context = canvas.getContext("2d");

? // context.translate(0,0);

? var context = canvas2.getContext("2d");

? // context.scale(2, 2);

? html2canvas(document.querySelector('body'), {

? canvas: canvas2,

? ? ? taintTest:true,

? ? ? useCORS:true,

? ? ? allowTaint:true

? }).then(function(canvas) {

? //此處html可換body,或div等

? //document.body.appendChild(canvas);

? //canvas轉(zhuǎn)換成url,然后利用a標(biāo)簽的download屬性,直接下載,繞過上傳服務(wù)器再下載

? document.querySelector(".down").setAttribute('href', canvas.toDataURL());

? });

? </script>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容