在H5、微信小程序中使用canvas绘制二维码、分享海报

在H5、微信小程序中使用canvas绘制二维码、分享海报



前言

提示:绘制二维码的插件有很多,有些仅支持H5,有些只适用微信小程序,故读者在使用二维码插件前需要先查看插件官方文档,查看其支持的环境

一、canvas绘制二维码

1.H5中使用canvas

  • H5中安装qrious插件
npm install --save qrious
  • 引入qrious
 <script>
    import Qrcode from "qrious";
 </srcipt>
  • canvas模板
<canvas @tap="createQrCode()" style="width: 400rpx; height:400rpx"
  id="canvas2D"
  canvas-id="canvas2D"
  class="canvas"
></canvas>
  • 初始化canvas
createQrCode() {
    
    
     let sharePath = "******";//需要编码为二维码的值
     let qr = new Qrcode({
    
    
         value: sharePath,
         size:800,
         background:'transparent',//二维码的背景颜色
         foreground:'black',//二维码的前景颜色
         // level:'L',	//二维码的误差校正级别(L, M, Q, H)
     });
     this.qrCodeSrc = qr.toDataURL(); //二维码地址
     //绘制海报
     this.$nextTick(() => {
    
    
         this.createSelectorQuery()
             .select("#canvas2D")
             .fields({
    
    
                 node: true,
                 size: true,
             })
             .exec(this.init.bind(this));
     });
  });
},
  • 二维码绘制并渲染
async init(res) {
    
    
  try {
    
    
        uni.showLoading({
    
     title: "生成中", mask: true });
        self = this;
        self.canvas = document.querySelector("canvas");
        let ctx = self.canvas.getContext("2d");
        let dpr = uni.getSystemInfoSync().pixelRatio;
        self.canvas.width = res[0].width * dpr;
        self.canvas.height = res[0].height * dpr; //画布放大后绘制比例也相应放大,这样绘图时就能按原尺寸计算
        let qrUrl = new Image();
        qrUrl.src = self.qrCodeSrc;
        qrUrl.onload = function () {
    
    
            ctx.drawImage(
                qrUrl,
                0,
                0,
                self.canvas.width/dpr,
                self.canvas.height/dpr
            );
        };
        uni.hideLoading();
    } catch (error) {
    
    
        uni.hideLoading();
        console.log(error, "init.error");
    }
 }

2.微信小程序中使用canvas

微信小程序中安装weapp-qrcode插件

npm install weapp-qrcode --save
  • 引入weapp-qrcode
 <script>
   import qrCode from 'weapp-qrcode';
 </srcipt>
  • canvas模板
<canvas style="z-index: 1;;width: 460rpx; height: 460rpx;"
	canvas-id="qrcode">
</canvas>
  • 二维码绘制并渲染
createQrCode() {
    
    
	let self = this;
	let px1 = 460 / 750 * wx.getSystemInfoSync().windowWidth;
	let content = "**********";//二维码内容
		//生成二维码
	new qrCode('qrcode', {
    
    
		text: content,
		width: px1,
		height: px1,
		showLoading: true, // 是否显示loading
		loadingText: '二维码生成中', // loading文字
		colorDark: '#000000',
		colorLight: '#FFFFFF',
		correctLevel: 3
	})
},

二、canvas绘制分享海报常用方法

  • 文字单行+…
/*
  str:要绘制的字符串
  canvas:canvas对象
  initX:绘制字符串起始x坐标
  initY:绘制字符串起始y坐标
  lineHeight:字行高 32
  canvasWidth:文字宽度
*/
canvasTextSingleLine(
	str,
	ctx,
	initX,
	initY,
	lineHeight,
	canvasWidth,
	textStyle
) {
    
    
	let strArr = str.split("");
	let row = [];
	let temp = "";
	for (let i = 0; i < strArr.length; i++) {
    
    
		if (ctx.measureText(temp).width < canvasWidth) {
    
    
			temp += strArr[i];
		} else {
    
    
			i--; //这里添加了i-- 是为了防止字符丢失,效果图中有对比
			row.push(temp);
			temp = "";
		}
	}
	row.push(temp); // row有多少项则就有多少行
	let showText=""//显示的文字
	//如果数组长度大于1,现在只需要显示一行则只截取第一项,把第一行结尾设置成\'...\'
	if (row.length >1) {
    
    
		let rowCut = row.slice(0, 1);
		let rowPart = rowCut[0];
		showText = rowPart + "..." //这里只显示一行,超出的用...表示;
	}
	ctx.fillText(row, initX, initY, canvasWidth);
	ctx.fillStyle = textStyle.color;
	ctx.textAlign = textStyle.align;
},
  • 文字换行
/*
 str:要绘制的字符串
  canvas:canvas对象
  initX:绘制字符串起始x坐标
  initY:绘制字符串起始y坐标
  lineHeight:字行高 32
  canvasWidth:文字宽度
*/
canvasTextAutoLine(
	str,
	ctx,
	initX,
	initY,
	lineHeight,
	canvasWidth,
	textStyle
) {
    
    
	var lineWidth = 0;
	var lastSubStrIndex = 0;
	for (let i = 0; i < str.length; i++) {
    
    
		lineWidth += ctx.measureText(str[i]).width;
		if (lineWidth > canvasWidth - initX) {
    
    
			ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY);
			initY += lineHeight;
			lineWidth = 0;
			lastSubStrIndex = i;
			this.wrapIndex++;
			console.log(241, this.wrapIndex);
		}
		if (i == str.length - 1) {
    
    
			ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
		}
		// ctx.font = "bold ".concat(textStyle.fontSize, "px Arial");
		ctx.fillStyle = textStyle.color;
		ctx.textAlign = textStyle.align;
	}
},
  • 绘制带圆弧的矩形
drawRoundedRect(ctx, x, y, w, h, r, dpr, fillStyle) {
    
    
	ctx.beginPath();
	ctx.moveTo(x + r, y);
	ctx.arcTo(x + w, y, x + w, y + h, r);
	ctx.arcTo(x + w, y + h, x, y + h, r);
	ctx.arcTo(x, y + h, x, y, r);
	ctx.arcTo(x, y, x + w, y, r);
	ctx.fillStyle = fillStyle; //设置填充颜色
	ctx.fill();
	ctx.closePath();
	},
  • 画一个圆形图片
circleImg(ctx, img, x, y, w, h, r) {
    
    
	//头像
	let size = 2 * r;
	ctx.save(); // 先保存状态 已便于画完圆再用
	ctx.beginPath(); //开始绘制
	//先画个圆
	ctx.arc(x, y, r, 0, Math.PI * 2);
	ctx.fill() //保证图片无bug填充
	ctx.clip(); //画了圆 再剪切 原始画布中剪切任意形状和尺寸
	ctx.drawImage(img, x - r, y - r, size, size) // 推进去图片
	ctx.restore();
},

**

觉得写得好的话记得点赞收藏+关注哦

**

猜你喜欢

转载自blog.csdn.net/weixin_45059911/article/details/129549337