1. 基本用法
<canvas>标签只有两个属性-----width和height
CSS:
<canvas class="qrcode" width="100%" height="100%"></canvas>
<canvas>元素只是创造了一个固定大小的画布,要想在它上面绘制内容,我们需要找到它的渲染上下文,
<canvas>元素有一个叫做 getContext()的方法,而这个方法就是用来获得渲染上下文和它的绘画功能。
JS:
imageToCanvsa () { let that = this let canvas = document.createElement('canvas') // 获取canvas对象(通过选择器选择canvas元素) let ctx = canvas.getContext('2d') // 获得渲染上下文和他的绘画功能 // 将二维码的canvas转化成base64 let qrcode = new Image () qrcode.crossOrigin = 'Anonymous' qrccode.src = document.querySelector('.qrcode').toDataURL() let img = new Image() img.crossOrigin = 'Anonymous' img.src = that.appData.share.img[that.currentIdx].img_url img.onload = fuction () { canvas.width = img.width // 画板宽 canvas.height =img.height // 画板高 // 画图 // 参数:图片对象、相对画布的起点x坐标、相对画布的起点y坐标、绘制的图片宽度(二维码,px)、绘制的图片高度(二维码,px) ctx.drawImage(img, 0, 0, img.width, img.height) ctx.drawImage(qrcode, img.width * 0.3, img.height * 0.65, img.width * 0.4, img.width * 0.4) ctx.fillStyle = '#fff' // 创建矩形 // 参数:绘制起点x坐标、绘制起点y坐标、矩形宽(像素)、矩形高() ctx.fillRect(img.width * 0.3, img.height * 0.878, img.width * 0.4, img.height * 0.035) ctx.fillStyle = '#000' ctx.font = 'normal 28px Arial' ctx.textBaseline = 'middle' // 文本基线在正中 // 在画布上绘制填色的文本 // 参数:规定在画布上输出的文本、开始绘制文本的x坐标、开始绘制文本的y坐标 ctx.fillText(`邀请码:${that.nikname}`, img.width * 0.5, img.height * 0.896) that.poster = canvas.toDataURL() } }