uniapp(小程序) 图片画布添加水印(加背景色)

一、页面

<template>
	<view>
        <view @click="creatPic">生成图片</view>
        <image :src="creatUrl" v-if="creatUrl"
           :style="{'width':'350px','height':cHeight+'px'}"> 
        </image>    
		<canvas :style="{'width': '350px','height': 
           cHeight+'px','position':'fixed','left':'100%'}" canvas-id="myCanvas"></canvas>
    </view>
</template>

<script>
export default {
	data() {
		return {
           cHeight:750,//画布高度
           url:'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
           //要加图片的水印
           creatUrl:''
		};
	},
	methods: {
       creatPic(){
          let obj = {
				src: this.url,
				first: `时间:2024-03-28`,
				second: `滴滴滴滴点`,
				three: `滴滴滴滴点2`,
				four: `滴滴滴滴点3`,
				five: `滴滴滴滴点4`,
			}
			let res = await this.getWatermark(obj)
            if(res.tempFilePath){
               this.creatUrl=res.tempFilePath
            }else{
               console.log('失败')
            }
       },
       getWatermark(obj) {
		 return new Promise((resolve, reject) => {
		 let that = this;
		 uni.getImageInfo({
		 src: obj.src,
		 success: (ress) => {
			let ctx = uni.createCanvasContext('myCanvas', that); //创建画布
			let width = 350
			let height = width / (ress.width / ress.height) //计算宽高比例
			that.cHeight = height
            ctx.drawImage(obj.src, 0, 0, width, height);
            ctx.fillStyle = "rgba(0,0,0,0.3)";
			ctx.fillRect(0, 0, width, 90); //为水印加了背景
			ctx.font = '12px Arial'
			ctx.setFillStyle('#FFFFFF') //字体颜色
			ctx.fillText(obj.first, 10, 20)
			ctx.fillText(obj.second, 10, 35)
			ctx.fillText(obj.three, 10, 50)
			ctx.fillText(obj.four, 10, 65)
			ctx.fillText(obj.five, 10, 80)
			ctx.draw(false, () => {
			  // setTimeout(() => { //制作复杂的水印需要时间,这里最好设置定时
				   uni.canvasToTempFilePath({ //内容转成图片
					  width: width, // 画布宽度
					  height: height, // 画布高度
					  x: 0,
					  y: 0,
					  fileType: 'jpg',//生成的图片类型
					  canvasId: "myCanvas",//canvasId
					  quality: 0.5,//图片质量
					  success: (res) => {
							resolve(res);
					  },
					  fail: (err) => {
							resolve(false);
					  }
					  }, that)
				// }, 200)
			 });
		  },
		  fail: (err) => {
			 resolve(false);
		  }
		})
	  })
	 }       
   }
};
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值