uniapp画图 uni.createcanvascontext

需求:分享图片,图片上下内容固定,中间内容动态获取

步骤:

1.用uni.createcanvascontext绘制图片

html

<canvas canvas-id="save-picture" v-if='toPicture' :disable-scroll="true"style="width: 350px;height: 520px;"></canvas>

js

//需要指定 canvasId,该绘图上下文只作用于对应的 <canvas/>
const ctx = uni.createCanvasContext("save-picture", this);
//第一个参数是canvasId,第二个参数自定义组件实例 this ,表示在这个自定义组件下查找拥有 canvas-id 的 <canvas/> ,如果省略,则不在任何自定义组件内查找

2.开始画图(部分代码)

ctx.setFillStyle('#fff'); // 背景颜色,相当于view的背景颜色
ctx.fillRect(0, 0, 350, 530) // fillRect(x,y,宽度,高度),相当于view的位置,宽高
let logoImgUrl = '/static/image/share_logo.png' //协会logo
ctx.drawImage(logoImgUrl , 10, 175, 100, 120) // drawImage(图片路径,x,y,绘制图像的宽度,绘制图像的高度)
ctx.setFontSize(16) // 字号
ctx.setFillStyle('#fff') // 字体颜色,默认黑色
ctx.fillText('编号:' + this.code,, 105, 30)//文字fillText(文字,x,y)
//走失详细信息 换行,超过两行隐藏
this.content = this.miss_time + '在' + this.address_detail + '走失'
/*canvas不能自动换行,需要自行计算 */
let _strlineW = 0;
let _strLastIndex = 0; //每次开始截取的字符串的索引
let _strHeight = 275; //绘制字体距离canvas顶部的初始高度
let _num = 1;
for (let i = 0; i < this.content.length; i++) {
    _strlineW += ctx.measureText(this.content[i]).width;
	if (_strlineW > this.canvasW - 125) {
	    if (_num == 2 && 2) {
		    //文字换行数量大于二进行省略号处理
			ctx.fillText(this.content.substring(_strLastIndex, i - 5) + '...', 120, _strHeight);
			_strlineW = 0;
			_strLastIndex = i;
			_num++;
			break;
		} else {
			ctx.fillText(this.content.substring(_strLastIndex, i), 120, _strHeight);
			_strlineW = 0;
			_strHeight += 20;
			_strLastIndex = i;
			_num++;
		}
	} else if (i == this.content.length - 1) {
		ctx.fillText(this.content.substring(_strLastIndex, i + 1), 120, _strHeight);
		_strlineW = 0;
	}
}

3.注意

绘制图片cxt.drawImage时图片路径只能是本地路径,若为网络地址可使用getImageInfo转换为本地路径,例:

var _this = this
uni.getImageInfo({
	src: _this.photo, //网络图片路径
	success(res) {
		_this.headImg = res.path
		console.log('本地路径', _this.headImg)
	}
})

若图片下层有背景颜色,需绘制块完成后再绘制图片,例:

// 4.绘制底部
ctx.setFillStyle('#808080'); // 默认白色
ctx.fillRect(0, 390, 350, 35) // fillRect(x,y,宽度,高度)
ctx.drawImage(ewmImgUrl, 255, 430, 80, 80) // drawImage(图片路径,x,y,绘制图像的宽度,绘制图像的高度)

4.生成图片。全部绘制完成后绘制图片

ctx.draw(true,() => {
    uni.canvasToTempFilePath({
        canvasId: "save-picture",
		width: 376 * 4,
		height: 500 * 4,
		quality: 1,
		fileType: 'jpg',
        success: (res) =>{
            console.log('绘制成功', res.tempFilePath);
            //生成图片后的逻辑方法
        }
    },_this)
})

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值