vue如何將html內(nèi)容轉(zhuǎn)為圖片并下載到本地
將html內(nèi)容轉(zhuǎn)為圖片并下載到本地
需求:將自己寫的html內(nèi)容轉(zhuǎn)化為圖片并可以下載到本地
1.安裝html2canvas
npm install --save html2canvas
2.在自己所需要的頁面進行引入
import html2canvas from "html2canvas";
3.html
<div class="popuptop" id="img"> ? ? <div class="pupupbg"> ? ? ? ? 內(nèi)容內(nèi)容內(nèi)容 ? ? </div> </div> ?<div class="weixin" @click="downimg"> ? ? ?<div class="weixinlogo" > ? ? ? ? ?<img src="../../assets/images/mypage/down.png"> ? ? ? ? ? <p class="weixinshare" >下載</p> ? ? ? </div> </div> <a id="downimg" href="" style=" rel="external nofollow" display:none"></a>
4.JS
//下載圖片
let downimg= ()=>{
? setTimeout(()=>{
? ? proxy.$nextTick(()=>{
? ? ? html2canvas(document.querySelector('#img'),{
? ? ? ? useCORS: true
? ? ? }).then(canvas => {
? ? ? ? var url = canvas.toDataURL() ? ? //把canvas轉(zhuǎn)成base64
? ? ? ? // 寫一個隱藏的按標簽,借助按標簽的download屬性下載圖片
? ? ? ? document.querySelector('#downimg').href = url
? ? ? ? document.querySelector('#downimg').download = "我的持倉報告.png"
? ? ? ? document.querySelector('#downimg').click()
? ? ? })
? ? })
? },2000)
}以上代碼就能實現(xiàn)將html內(nèi)容轉(zhuǎn)為圖片并下載到本地。
vue將html頁面轉(zhuǎn)為圖片并且下載該圖片
1.下載 html2canvas
npm install html2canvas
2.對應(yīng)頁面引入該插件
import html2canvas from 'html2canvas';
3.具體用法 (要element使用帶有一些(可選)選項的 html2canvas 呈現(xiàn),只需調(diào)用html2canvas(element, options);)
html2canvas(document.body).then(function(canvas) {
? ? document.body.appendChild(canvas);
});4.轉(zhuǎn)為圖片并且下載
<template> ?? ?<div> ?? ??? ?<div class="container" ref="imageDom">hahahah</div> ?? ??? ?<button @click="toImage">導(dǎo)出</button> ?? ?</div> </template>
在methods方法中:
toImage() {
? ? html2canvas(this.$refs.imageDom, {
? ? ? ? backgroundColor: '#ffffff'
? ? }).then(canvas => {
? ? ? ? var imgData = canvas.toDataURL("image/jpeg");
? ? ? ? this.fileDownload(imgData);
? ? })
},
fileDownload(downloadUrl) {
? ? let aLink = document.createElement("a");
? ? aLink.style.display = "none";
? ? aLink.href = downloadUrl;
? ? aLink.download = "監(jiān)控詳情.png";
? ? // 觸發(fā)點擊-然后移除
? ? document.body.appendChild(aLink);
? ? aLink.click();
? ? document.body.removeChild(aLink);
},效果圖:

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
ElementUI日期選擇器時間選擇范圍限制的實現(xiàn)
在日常開發(fā)中,我們會遇到一些情況,限制日期的范圍的選擇,本文就詳細的介紹了ElementUI日期選擇器時間選擇范圍限制的實現(xiàn),文中通過示例代碼介紹的非常詳細,感興趣的可以了解一下2022-04-04
vue3中的reactive、readonly和shallowReactive使用詳解
在 Vue3 中,可以使用 shallowReactive 函數(shù)創(chuàng)建一個淺層響應(yīng)式對象,它接收一個普通對象作為參數(shù),返回一個淺層響應(yīng)式代理對象,本文給大家介紹vue3中的reactive、readonly和shallowReactive使用,感興趣的朋友跟隨小編一起看看吧2024-04-04
三步搞定:Vue.js調(diào)用Android原生操作
這篇文章主要介紹了三步搞定:Vue.js調(diào)用Android原生操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

