下面以百度小程序为例,使用canvas生成海报
组件
canvas
api
swan.createCanvasContext
属性/方法
开始之前
废话不多说,上代码
index.swan
.container{background-color:#f1f1f1;}.main{width:750rpx;height:100vh;box-sizing:border-box;padding:20rpx40rpx;}index.js
逻辑
首先创建canvas上下文对象-ctx=this.createCanvasContext('myCanvas');
创建一个矩形作为背景
letcanvasWidth=app.globalData.windowWidth-40;//letcanvasHeight=canvasWidth+100+100+50;ctx.setFillStyle('#fff');//设置矩形的填充颜色为蓝色ctx.fillRect(0,0,canvasWidth,canvasHeight);//x偏移0,y偏移0,canvasWidth矩形宽,canvasHeight矩形高开始绘制海报中需要的元素
lethead_left=canvasWidth*0.6;lethead_center=canvasWidth*0.15;lethead_right=canvasWidth*0.25-10;ctx.drawImage('../../static/images/head_bg.jpg',0,0,canvasWidth,100);ctx.drawImage('../../static/images/dfhm.png',10,15,head_left,70);ctx.drawImage('../../static/images/zb.png',head_left+head_center,15,head_right,35);//先前提到的由于canvas不能设置靠右//要适配不同的微小偏差的机型,使用百分比的形式进行偏移//绘制的图像不要忘记给宽高,图像支持相对路径,网络图片,临时文件如何将元素居中
//我们可以得知上面矩形的高是100,我们想将矩形放到下面矩形的正中间//我们就需要设置小矩形的中心点//计算大矩形中心坐标-由于默认坐标是左上,也就是默认情况下的0,0,我们需要将坐标设置到大矩形中心letrectCenterX=canvasWidth/2;letrectCenterY=canvasWidth/2+100;ctx.setFillStyle('#ccc');//rectCenterX-100,rectCenterY-100将坐标进行偏移-相当于以rectCenterX-100,rectCenterY-100,为起始点画200*200的正方形ctx.drawImage('../../static/images/head_bg.jpg',rectCenterX-100,rectCenterY-100,200,200);ctx.fillRect(0,canvasWidth+100,canvasWidth,50);ctx.setFillStyle('#000');ctx.setFontSize(24);ctx.setTextAlign('center');ctx.fillText('商品名称',rectCenterX,canvasWidth+100+24+10)如何将文本自动换行
关于如何将绘制的canvas保存成临时文件,那就是另一个api了