之前我們簡單的了解了canvas的基本用法,這里我們來了解下如何將html內(nèi)容寫入到canvas中生成圖片,這里我使用到了html2canvas插件,這個插件是基于canvas實現(xiàn)的
html2canvas官網(wǎng): http://html2canvas.hertzen.com/
一:下載html2canvas插件
1:直接下載html2canvas插件
直接點擊html2canvas.min.js,然后直接ctrl+s進行保存即可
2:使用npm進行下載
npm install html2canvas
二:html2canvas使用介紹
在html2canvas中主要使用兩種方法
1:將html內(nèi)容寫入到canvas中
html2canvas(element,options).then((canvas) =>{})
參數(shù)說明:
element:需要將html內(nèi)容寫入canvas的jQuery對象
options:配置信息
常用的配置基本信息:
scale:縮放比例,默認為1
allowTaint:是否允許跨域圖像污染畫布,默認為false
useCORS:是否嘗試使用CORS從服務(wù)器加載圖像,默認為false
width:canvas畫布的寬度,默認為jQuery對象的寬度
height:canvas畫布的高度,默認為jQuery對象的高度
backgroundColor:/畫布的背景色,默認為透明(#fff),參數(shù)可以為#表示的顏色,也可以使用rgba
2:將canvas畫布信息轉(zhuǎn)化為base64格式圖片
canvas.toDataURL("image/png")
如果你的html內(nèi)容中有指定的內(nèi)容不寫入到canvas中的話,你可以給標簽添加如下屬性
data-html2canvas-ignore="true"
三:簡單實例
1:引入html2canvas
<script src="js/html2canvas.min.js"></script>
或者使用import引入html2canvas
import html2canvas from 'html2canvas';
2:需要轉(zhuǎn)化的的html內(nèi)容
<div class="capture"> <img src="./wj.jpg" alt=""> <div> <span style="color: #f00;letter-spacing: 20px">這是文字文字</span> <span data-html2canvas-ignore="true">不寫入canvas</span> </div> </div>
3:將html內(nèi)容寫入canvas并轉(zhuǎn)化為base64圖片
html2canvas(document.getElementsByClassName("capture")[0], { scale: 2,//縮放比例,默認為1 allowTaint: false,//是否允許跨域圖像污染畫布 useCORS: true,//是否嘗試使用CORS從服務(wù)器加載圖像 width: '500',//畫布的寬度 height: '500',//畫布的高度 backgroundColor: '#000000',//畫布的背景色,默認為透明 }).then((canvas) => { //將canvas轉(zhuǎn)為base64格式 var imgUri = canvas.toDataURL("image/png"); }); 這里注意jQuery對象是do
這里注意jQuery對象是document.getElementsByClassName("capture")[0]而不是document.getElementsByClassName("capture"),document.getElementsByClassName("capture")是DOM原生對象而不是jQuery對象
根據(jù)如上就可以實現(xiàn)將html內(nèi)容寫入canvas并轉(zhuǎn)化為base64圖片,這時候我們就可以將base64內(nèi)容傳到服務(wù)端,服務(wù)端可以將圖片進行保存起來
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標簽:盤錦 阿壩 金昌 赤峰 綏化 萍鄉(xiāng) 聊城 中山
巨人網(wǎng)絡(luò)通訊聲明:本文標題《使用html2canvas實現(xiàn)將html內(nèi)容寫入到canvas中生成圖片》,本文關(guān)鍵詞 使用,html2canvas,實,現(xiàn)將,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。