小猿圈web前端簡(jiǎn)述canvas如何實(shí)現(xiàn)二維碼和圖片合成

你經(jīng)常看到活動(dòng)海報(bào)什么的,上都是有各種宣傳文案以及二維碼形成的,你知道怎么用canvas實(shí)現(xiàn)二維碼和圖片合成,下面小猿圈Linux講師為你詳細(xì)介紹一下canvas如何實(shí)現(xiàn)二維碼和圖片合成的。

使用url生成一個(gè)二維碼,然后和另外一張圖片合成一張圖。實(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 (

? ? ? ? ? ? <div>

? ? ? ? ? ? ? ? <img? alt='mix_img' id='mix_img'/>

? ? ? ? ? ? </div>

? ? ? ? )

? ? }

}

以上就是小猿圈Linux講師為你講解的canvas如何實(shí)現(xiàn)二維碼和圖片合成的,很多人在學(xué)習(xí)前端的過(guò)程中,極大部分剛?cè)腴T(mén)或者在從事前端的小伙伴,在學(xué)習(xí)的過(guò)程中遇到很多難題難以解決,或者很難發(fā)現(xiàn)自己的問(wèn)題所在,耗費(fèi)很大精力也無(wú)法得到提升。可以到小猿圈為你解決問(wèn)題,并且?guī)椭闾嵘殬I(yè)技能。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容