<template>
<view>
<image class="ewm"
:style="{ width: canvasObj.w + 'px', height: canvasObj.h + 'px' }"
:src="downPic"
:show-menu-by-longpress="true"
@longpress="shareBind(downPic)"></image>
<canvas
type="2d"
id="canvas"
class="canvas"
canvas-id="canvas"
:style="{ width: canvasObj.w + 'px', height: canvasObj.h + 'px' }"
></canvas>
</view>
</template>
<script>
export default {
data() {
return {
bgImg:"http://rjj9us0vs.hn-bkt.clouddn.com/tmp/qRrJMd3xzXbi76863eb670e93a8b8fb4a1fb61604074.png",
codeImg:"http://rjj9us0vs.hn-bkt.clouddn.com/tmp_aa0b83b6e2e28ef8d36c76e156b955c7f8bae4eea8f74ba0.jpg",
canvasObj: {
w: 375,
h: 800,
},
ctx: null,
canvas: null,
downPic:"",
}
},
onShow(){;
this.darwAwardFn();
},
methods: {
async darwAwardFn() {
let that=this;
uni.createSelectorQuery()
.select('#canvas')
.fields({ node: true, size: true })
.exec((res) => {
//开始画图
console.log('获取到的canvas元素res', res)
that.canvas = res[0].node
that.canvas.width = that.canvasObj.w
that.canvas.height = that.canvasObj.h
that.ctx = that.canvas.getContext('2d')
that.canvasDraw().then(res=>{
console.log('1',res)
// 向画布载入logo的方法
return that.code()
}).then(rrr=>{
console.log('2',rrr)
//图片头像渲染完成之后,渲染文字
that.txt()
}).then(()=>{
that.canvasImg();
})
})
},
// 设置背景图
canvasDraw() {
let that=this;
return new Promise(res=>{
let img = that.canvas.createImage(); //创建img对象
img.src =that.bgImg;
img.onload = () => {
console.log(img.complete); //true
that.ctx.drawImage(img, 0, 0,that.canvasObj.w, that.canvasObj.h);
setTimeout(() => {
res(true)
}, 100);
};
})
},
code() {
let that=this;
return new Promise(rrr=>{
let code = that.canvas.createImage(); //创建img对象
code.src =that.codeImg;
code.onload = () => {
that.ctx.drawImage(code, 175,220, 110, 110);
};
setTimeout(() => {
rrr(true)
}, 100);
})
},
txt() {
let that=this;
let text = '接小程序开发,web开发,H5开发,小程序云开发,PHP开发'
let moy = '有需要的直接微信扫码'
that.ctx.font = 'normal bold 12px sans-serif';
that.ctx.fillStyle = "rgba(60, 59, 59)";
console.log('======,', text.length)
let firstLine = text.substring(0, 20); //文字切割方法
let secondLine = text.substring(20, 38);
that.ctx.fillText(firstLine, 10, 275, 280)
that.ctx.fillText(secondLine, 10, 290, 280)
that.ctx.fillStyle = "rgba(0,0,0)";//添加颜色
that.ctx.font = 'normal bold 16px sans-serif';//指定文字样式
that.ctx.fillStyle = "red"; //新增样式
that.ctx.fillText(moy, 10, 315, 280) // ctx.fillText(文字, 像素, 移动y, 移动x)
},
//canvas生成图片
canvasImg() {
let that=this;
uni.canvasToTempFilePath({
canvas:that.canvas,
success: function (res) {
console.log('生成图片成功:')
console.log(res)
that.downPic = res.tempFilePath
}
})
},
}
}
</script>
<style>
.ewm{
position:absolute;
z-index:10;
top:0;
left:0;
display:block;
}
</style>