這篇文章主要介紹canvas實(shí)現(xiàn)二維碼和圖片合成的方法,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)是一家專業(yè)提供高明企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站設(shè)計(jì)、做網(wǎng)站、html5、小程序制作等業(yè)務(wù)。10年已為高明眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。
實(shí)現(xiàn)思路是這樣的
使用jr-qrcode將url生成data:base64供img使用
然后使用canvas 將兩張圖合成一張圖片
遇到的問(wèn)題
生成圖片之后發(fā)現(xiàn)圖片很模糊,解決辦法是將canvas畫(huà)布擴(kuò)大兩倍,其他參數(shù)也夸大兩倍就可以了
jr-qrcode 可以使用npm install --save jr-qrcode 安裝這個(gè)包
作用就是可以轉(zhuǎn)化text到data:base64 供img的src 使用
代碼如下:
import React, { Component } from 'react' const qrcode = require('jr-qrcode') const loadImg = (src) => { const paths = Array.isArray(src) ? src : [src]; const promise = []; paths.forEach((path) => { promise.push(new Promise((resolve, reject) => { let img = new Image(); img.crossOrigin = "Anonymous"; img.src = path; img.onload = () => { resolve(img); }; img.onerror = (err) => { console.log('圖片加載失敗') } })) }); return Promise.all(promise); } const getImageData = (url, src) => { const imgsrc = qrcode.getQrBase64(url) let canvas = document.createElement('canvas') const width = document.documentElement.clientWidth const height = document.documentElement.clientHeight canvas.width = width*2 canvas.height = height*2 let ctx = canvas.getContext("2d") loadImg([imgsrc, src]).then(([img1, img2]) => { ctx.drawImage(img2, 0, 0, width*2, height*2) ctx.drawImage(img1, width-80, height*2-220, 200, 160) ctx.fillStyle = 'rgba(0,0,0,0.3)'; ctx.fillRect(width-80, height*2-60, 200, 40); ctx.save() ctx.font="28px Arial" ctx.fillStyle = '#fff'; ctx.fillText('長(zhǎng)按識(shí)別二維碼', width-80, height*2-30, 200, 160) let imageURL = canvas.toDataURL("image/png") document.getElementById('mix_img').setAttribute('src',imageURL) }) } export default class QRcode extends Component { render() { const { url , picSrc} = this.props getImageData(url,picSrc) return () } }
![]()
以上是canvas實(shí)現(xiàn)二維碼和圖片合成的方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!