canvas实现二维码和图片合成
上个版本街道一个需求,使用url生成一个二维码,然后和另外一张图片合成一张图拍你,
实现思路是这样的
- 使用jr-qrcode将url生成data:base64供img使用
- 然后使用canvas 将两张图合成一张图片
遇到的问题
生成图片之后发现图片很模糊,解决办法是将canvas画布扩大两倍,其他参数也夸大两倍就可以了
jr-qrcode 可以使用npm install --save jr-qrcode 安装这个包
作用就是可以转化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('长按识别二维码', 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 ( <div> <img alt='mix_img' id='mix_img'/> </div> ) } }
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25