前端图片合成并下载

// 安装
// npm i --save composite-image
import CompositeImage from 'composite-image';
export default {
  name: 'App',
  mounted() {
    const image = new CompositeImage({
      bgWidth: 300,  // 合成后图片的宽度
      bgHeight: 400,  // 合成后图片的高度
    });
    /**
     * @description 第一张图片
     * @src 图片链接
     * @x 相对于画布的x坐标
     * @y 相对于画布的y坐标
     * @width 图片的宽
     * @height 图片的高
     */
    const cfg1 = {
      src: 'https://bpic.588ku.com/back_pic/19/04/14/bf310e139cf9fc16b3c032caccf6804a.jpg',
      x: 0,
      y: 0,
       300,
      height: 300
    };
    /**
     * @description 第二张图片
     * @src 图片链接
     * @x 相对于画布的x坐标
     * @y 相对于画布的y坐标
     * @width 图片的宽
     * @height 图片的高
     */
    const cfg2 = {
      src: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1805103632,2396162225&fm=26&gp=0.jpg',
      x: 90,
      y: 70,
       116,
      height: 116
    };
    image.composite(cfg1, cfg2).then(() => {
    image.ctx.fillStyle='#E7CE86' // 设置字体颜色
    image.ctx.font = '30px Adobe Ming Std' // 字体样式
    // 计算文字宽度
    let num = 0
    this.shopName.split('').forEach(item=>{
     if(/^[a-zA-Z]*$/.test(item) || /^[0-9]*$/.test(item))
     {
    num+=0.5
      }
     else if(/^[u4e00-u9fa5]*$/.test(item))
    {
    num ++
    }
    })
    image.ctx.fillText('#'+this.shopName+'#',(720 - num*30)/2-18,200); // 文字和位置 text,x,y

    image.print(); // 图片地址dataUrl格式,可传入生成图片类型,默认'png'

      image.download('image.png'); // 将已生成图片下载至本地,可传入导出的文件名
    })
  }
}

模块地址:https://www.npmjs.com/package/composite-image

原文地址:https://www.cnblogs.com/onlywu/p/14428809.html