在項目中常常會遇到須要將不一樣的二維碼放到一張通用圖片上,提供用戶下載
簡單來講,就是利用canvas將同等比例的二維碼在圖片上疊加,生成海報canvas
通常來講海報背景都是固定的,能夠直接放在public文件夾,二維碼可根據後臺返回數據,也可用canvas生成,在此很少贅述跨域
import posterBgImg from '../public/images/poster_bg.png';// 海報底圖 import qrcodeImg from '../public/images/qrcode.png';// 二維碼 export default{ name: 'qrcode-in-poster', data(){ return { posterBgImg, qrcodeImg, posterSize: 930/650,// 海報高寬比例 qrCodeSize: {// 二維碼與海報對應比例 =》 用於設置二維碼在海報中的位置 width: 270/650, height: 270/930, left: 190/650, top: 448/650 }, poster: '',// 合成圖片 } } };
限定移動端最大寬度爲 480px瀏覽器
computed: { screenWidth(){ let w = document.body.clientWidt || document.documentElement.clientWidth || 375; return w > 480 ? 480 : w ; } };
methods: { combinedPoster(_url){ let that = this, qrcode = this.qrcodeImg; // 二維碼地址 console.log("open draw: ", _url, qrcode) let base64 = '', canvas = document.createElement('canvas'), ctx = canvas.getContext("2d"), _w = this.screenWidth * 2, // 圖片寬度: 因爲手機屏幕時retina屏,都會多倍渲染,在此只設置2倍,若是直接設置等於手機屏幕,會致使生成的圖片分辨率不夠而模糊 _h = this.posterSize * _w, // 圖片高度 _qr_w = this.qrCodeSize.width * _w, // 二維碼寬 = 比例 * 寬度 _qr_h = this.qrCodeSize.height * _h, // 二維碼高 = 比例 * 高度 _qr_t = this.qrCodeSize.top * _w, // 二維碼頂部距離 = 比例 * 寬度 _qr_l = this.qrCodeSize.left * _w; // 二維碼左側距離 = 比例 * 寬度 // 設置canvas寬高 canvas.width = _w; canvas.height = _h; ctx.rect(0, 0, _w, _h); ctx.fillStyle = '#fff'; // 填充顏色 ctx.fill(); // 迭代生成: 第一層(底圖)+ 第二層(二維碼) // file:文件,size:[頂部距離,左側距離,寬度,高度] let _list = [ { file: _url, size: [0, 0, _w, _h] }, { file: qrcode, size: [_qr_l, _qr_t, _qr_w, _qr_h] } ]; // 開始繪畫 let drawing = (_index) => { // 判斷當前索引 =》 是否已繪製完畢 if (_index < _list.length) { // 等圖片預加載後畫圖 let img = new Image(), timeStamp = new Date().getTime(); // 防止跨域 img.setAttribute('crossOrigin', 'anonymous') // 連接加上時間戳 img.src = _list[_index].file + '?' + timeStamp img.onload = function() { // 畫圖 ctx.drawImage(img, ..._list[_index].size) // 遞歸_list drawing(_index + 1) } } else { // 生成圖片 base64 = canvas.toDataURL("image/png") if (base64) { // 賦值相應海報上 this.$set(that, 'poster', base64) } } } drawing(0) } };
mounted(){ // 須要合成海報的圖片 this.draw(this.posterBgImg) }
點擊下載合成圖片微信
methods: { handleDownload(){ if(this.poster){ let a = document.createElement("a"); a.setAttribute("download", "海報下載-"+(new Date().getTime())); a.href = this.poster a.click() }else{ console.log("海報不存在,請從新生成!") } } }
tips:不適用於微信瀏覽器,只能提示用戶長按保存。post