現在有很多微信公眾號運營活動,都有生成圖片的需求,生成圖片后可以發送給好友和發到朋友圈擴散,利于產品的宣傳!
1.生成圖片可以用canvas,但是由于已經有了html2canvas這個開源庫,所以為了節省時間就沒有自己寫了
github地址: html2canvas
少啰嗦,先看東西!!!
LiveDemo
/**
* 根據window.devicePixelRatio獲取像素比
*/
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
/**
* 將傳入值轉為整數
*/
function parseValue(value) {
return parseInt(value, 10);
};
/**
* 繪制canvas
*/
async function drawCanvas (selector) {
// 獲取想要轉換的 DOM 節點
const dom = document.querySelector(selector);
const box = window.getComputedStyle(dom);
// DOM 節點計算后寬高
const width = parseValue(box.width);
const height = parseValue(box.height);
// 獲取像素比
const scaleBy = DPR();
// 創建自定義 canvas 元素
var canvas = document.createElement('canvas');
// 設定 canvas 元素屬性寬高為 DOM 節點寬高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 設定 canvas css寬高為 DOM 節點寬高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 獲取畫筆
const context = canvas.getContext('2d');
// 將所有繪制內容放大像素比倍
context.scale(scaleBy, scaleBy);
let x = width;
let y = height;
return await html2canvas(dom, {canvas}).then(function () {
convertCanvasToImage(canvas, x ,y)
})
}
/**
* 圖片轉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.由于現在的手機都是高清屏,所以如果你不做處理就會出現模糊的情況,為什么會出現模糊的情況?這個就涉及到設備像素比 devicePixelRatio js 提供了 window.devicePixelRatio 可以獲取設備像素比
function DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
這個DPR函數就是獲取設備的像素比, 那獲取像素比之后要做什么呢?
var canvas = document.createElement('canvas');
// 設定 canvas 元素屬性寬高為 DOM 節點寬高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 設定 canvas css寬高為 DOM 節點寬高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// 獲取畫筆
const context = canvas.getContext('2d');
// 將所有繪制內容放大像素比倍
context.scale(scaleBy, scaleBy);
3.獲取設備像素比之后將canavs.width 和 canvas.height 去乘以設備像素比 也就是 scaleBy; 這個時候在去設置canvas.style.width 和 canvas.style.height 為dom的寬和高。想想為什么要這么寫?最后在繪制的餓時候將所繪制的內容放大像素比倍
舉個例子iphone6S是設備寬高是375 X 667 ,6S的 window.devicePixelRatio = 物理像素 / dips(2=750/375)所以設計師一般給你的設計稿是不是都是750*1334的?所以如果按照一比一去繪制在高清屏下就會模糊,看圖說話6S DPR=2

6plus DPR=3

4.最后調用canvas.toDataURL("image/png");賦值給image.src,由于微信里面無法保存圖片,所以只能生成圖片文件,調用微信自帶的長按保存到圖片到相冊功能,如圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。