需求:先设置画布的宽高,再将每个图片整理成一个对象的数组通过某个方法传出合成后的base64
```
//画布的大小
{
bgWidth:'画布的宽',
bgHeight:'画布的高'
}
//图片的配置
[{
src:"图片的base64",
x:'放入画布的x坐标',
y:'放入画布的y坐标',
height:'设置传入图片的高度',
width:'设置传入图片的宽度'
}]
```
-
具体思路
(1)、创建一个画布的类,他的属性是canvas虚拟dom和ctx
(2)、构造器初始化convas对象、ctx、convas的宽高
(3)、这个类应该有将配置的对象数组合成图片的方法和导出画布base64的方法
-
(1)、创建实现功能的类
``` //将base64转成虚拟dom的功能 function getImage(url){ const image=new window.image() if(/^http/.test(url)){ image.setAttribute('crossOrigin','anonymous') } image.src=url return new Promise((resolve,reject)=>{ image.onload=function (){ return resolve(image) } image.error=function (){ return resolve(null) } }) } class compoundImgs{ convas:any ctx:any constructor({bgWidth:number,bgHeight:number}){ this.convas=document.createElement('canvas') this.canvas.width=bgWidth this.canvas.height=bgHeight this.ctx=this.canvas.git Context('2d') } async run(imgConfigs){ //获取Dom节点promise对象形成的数组 const imgDomsP=imgConfigs.map(async ({src})=>{ const imgDom = await getImage(src) return imgDom }) //dom节点数组 const imgEles=await Promise.all(imgDomsP) //遍历画图 imgEles.map((ele,i)=>{ const {x=0,y=0,width=0,height=0}=imgConfigs[i] if(ele){ this.ctx.drawImage(ele,x,y,width,height) } }) } //打印画布base64 print(){ return this.canvas.toDataURL() } } export default compoundImgs ```(2)、使用
const mycanvas=new compoundImgs({ bgWidth:1080,bgHeight:1920}) mycanvas.run([{src:图片A的base64, x:A的x坐标, y:A的y坐标, height:A的高, width:A的宽 },{src:图片B的base64, x:B的x坐标, y:B的y坐标, height:B的高, width:B的宽 }]).then(()=>{ console.log(mycanvas.print() })