JavaScript之移動端H5生成圖片解決方案講解
現(xiàn)在有很多微信公眾號運營活動,都有生成圖片的需求,生成圖片后可以發(fā)送給好友和發(fā)到朋友圈擴散,利于產(chǎn)品的宣傳!
1.
生成圖片可以用canvas,但是由于已經(jīng)有了html2canvas這個開源庫,所以為了節(jié)省時間就沒有自己寫了
github地址: html2canvas
LiveDemo
/** * 根據(jù)window.devicePixelRatio獲取像素比 */ function DPR() { if (window.devicePixelRatio && window.devicePixelRatio > 1) { return window.devicePixelRatio; } return 1; } /** * 將傳入值轉(zhuǎn)為整數(shù) */ function parseValue(value) { return parseInt(value, 10); }; /** * 繪制canvas */ async function drawCanvas (selector) { // 獲取想要轉(zhuǎn)換的 DOM 節(jié)點 const dom = document.querySelector(selector); const box = window.getComputedStyle(dom); // DOM 節(jié)點計算后寬高 const width = parseValue(box.width); const height = parseValue(box.height); // 獲取像素比 const scaleBy = DPR(); // 創(chuàng)建自定義 canvas 元素 var canvas = document.createElement('canvas'); // 設定 canvas 元素屬性寬高為 DOM 節(jié)點寬高 * 像素比 canvas.width = width * scaleBy; canvas.height = height * scaleBy; // 設定 canvas css寬高為 DOM 節(jié)點寬高 canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; // 獲取畫筆 const context = canvas.getContext('2d'); // 將所有繪制內(nèi)容放大像素比倍 context.scale(scaleBy, scaleBy); let x = width; let y = height; return await html2canvas(dom, {canvas}).then(function () { convertCanvasToImage(canvas, x ,y) }) } /** * 圖片轉(zhuǎn)base64格式 */ function convertCanvasToImage(canvas, x, y) { let image = new Image(); let _container = document.getElementsByClassName('container')[0]; let _body = document.getElementsByTagName('body')[0]; image.width = x; image.height = y; image.src = canvas.toDataURL("image/png"); _body.removeChild(_container); document.body.appendChild(image); return image; } drawCanvas('.container')
2.
由于現(xiàn)在的手機都是高清屏,所以如果你不做處理就會出現(xiàn)模糊的情況,為什么會出現(xiàn)模糊的情況?這個就涉及到設備像素比 devicePixelRatio js 提供了 window.devicePixelRatio 可以獲取設備像素比
function DPR() { if (window.devicePixelRatio && window.devicePixelRatio > 1) { return window.devicePixelRatio; } return 1; }
這個DPR函數(shù)就是獲取設備的像素比, 那獲取像素比之后要做什么呢?
var canvas = document.createElement('canvas'); // 設定 canvas 元素屬性寬高為 DOM 節(jié)點寬高 * 像素比 canvas.width = width * scaleBy; canvas.height = height * scaleBy; // 設定 canvas css寬高為 DOM 節(jié)點寬高 canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; // 獲取畫筆 const context = canvas.getContext('2d'); // 將所有繪制內(nèi)容放大像素比倍 context.scale(scaleBy, scaleBy);
3.
獲取設備像素比之后將canavs.width 和 canvas.height 去乘以設備像素比 也就是 scaleBy; 這個時候在去設置canvas.style.width 和 canvas.style.height 為dom的寬和高。想想為什么要這么寫?最后在繪制的餓時候?qū)⑺L制的內(nèi)容放大像素比倍
舉個例子iphone6S是設備寬高是375 X 667 ,6S的 window.devicePixelRatio = 物理像素 / dips(2=750/375)所以設計師一般給你的設計稿是不是都是750*1334的?
所以如果按照一比一去繪制在高清屏下就會模糊,看圖說話6S DPR=2
6plus DPR=3
4.
最后調(diào)用canvas.toDataURL("image/png");賦值給image.src,由于微信里面無法保存圖片,所以只能生成圖片文件,調(diào)用微信自帶的長按保存到圖片到相冊功能
到此這篇關于JavaScript之移動端H5生成圖片解決方案講解的文章就介紹到這了,更多相關JavaScript之移動端H5生成圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!