微信小程序生成海报下载到本地手机本地

 里面有注释,这个就不详细说了,把对应的的图片路径换掉,就可以完成运行了

index.js

const server = require("../../utils/server");
const config = require("../../utils/config");
const {
  $Toast
} = require('../../component/iview/base/index');
const ctx = wx.createCanvasContext('shareCanvas');
Page({
  data: {
    canvasWidth: "",
    canvasHeight: "",
    canvasLeft: "",
    canvasTop: "",
    imgSrc: null,
    albumsDetail: '',
    albumsDescribe: '',
    pictureList: [],
    visible: false,
    albumsId: '',
    networkStatus: true, //网络状态 
    actions: [{
        name: '取消',
        color: '#666',
      },
      {
        name: '去设置',
        color: '#19be6b'
      }
    ]
  },
  /* 
  获取图片,一般我们生成海报,海报上的二维码都是动态生成的,每次生成的二维码都不一样,且都是通过后台返回的图片地址。
  包括海报背景也是动态,后台返回会来的。所以我们现下载图片,生成临时路径。
  使用promise主要是海报可能有多个图片组成,必须等图片全部下载完成再去生成
  */
  onLoad: function(options) {
  },

  // 专辑详情获取海报内容的(这个本来是后台请求的接口,这里就不显示了)
 
  //获取纯文本方法(这个方法只是用来把后台富文本的内容转换成纯文本)
  removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str = str.replace(/ /ig, ''); //去掉 
    str = str.replace(/\s/g, ''); //将空格去掉
    return str;
  },

  getImage: function(url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: function(res) {
          resolve(res)
        },
        fail: function() {
          reject("")
        }
      })
    }).catch((e) => {});
  },
  getImageAll: function(image_src) {
    let that = this;
    var all = [];
    image_src.map(function(item) {
      all.push(that.getImage(item))
    })
    return Promise.all(all)
  },
  //创建
  create: function() {
    let that = this;
    //图片一把是通过接口请求后台,返回俩点地址,或者网络图片(这里对应的图片换成你自己的图片和文字)
    let bg = 'https://cdn.nailtutu.com/wechat/Rectangle.png';
    let qr = 'https://cdn.nailtutu.com/wechat/wechat_QRCode.jpg';
    let url = config.imgUrl + that.data.albumsDetail.galleryUrl
    let url1 = config.imgUrl + that.data.pictureList[0].galleryUrl
    let logo = config.imgUrl + that.data.albumsDetail.authorHeadPortrait
    let url2,url3;
    if (that.data.pictureList.length < 3) {
       url2 = config.imgUrl + that.data.pictureList[0].galleryUrl
       url3 = config.imgUrl + that.data.pictureList[0].galleryUrl
    } else {
       url2 = config.imgUrl + that.data.pictureList[1].galleryUrl
       url3 = config.imgUrl + that.data.pictureList[2].galleryUrl
    }
    //图片区别下载完成,生成临时路径后,在尽心绘制
    this.getImageAll([bg, qr, url, url1, url2, url3, logo]).then((res) => {
      let bg = res[0];
      let qr = res[1];
      let url = res[2];
      let url1 = res[3];
      let url2 = res[4];
      let url3 = res[5];
      let logo = res[6]
      //设置canvas width height position-left,  为图片宽高
      this.setData({
        canvasWidth: bg.width + 'px',
        canvasHeight: bg.height-100 + 'px',
        canvasLeft: `-${bg.width + 100}px`,
      })
      let ctx = wx.createCanvasContext('canvas');
      ctx.drawImage(bg.path, 0, 0, bg.width, bg.height-100);

      // 美甲涂涂logo
      ctx.drawImage('../../images/logo.png', 170, 20, 68, 68);
      ctx.setFontSize(30);
      ctx.setFillStyle('#000');
      ctx.fillText("美甲涂涂,更多乐趣", 280, 65);
      //头部
      ctx.drawImage(url.path, 0, 100, bg.width, bg.width);
      //专辑名称
      ctx.setFontSize(38);
      ctx.setFillStyle('#000');
      ctx.fillText(that.data.albumsDetail.albumsTitle, 30, 920)
      // 画圆
      ctx.save();
      ctx.beginPath();
      ctx.arc(60, 980, 30, 0, Math.PI * 2, false);
      ctx.closePath();
      ctx.clip();
      ctx.stroke()
      // 作者 logo
      ctx.drawImage(logo.path, 30, 950, 60, 60);
      ctx.restore();
      ctx.save();
      // 作者名称
      ctx.setFontSize(30)
      ctx.setFillStyle('#000')
      ctx.fillText(that.data.albumsDetail.authorNickname, 110, 990);
      ctx.fillText(that.data.albumsDetail.createTime, 620, 990);

      // 标题
      ctx.drawImage('../../images/Group4.png', 220, 1030, 50, 30);
      ctx.setFontSize(40);
      ctx.setFillStyle('#000');
      ctx.fillText("设计说明", 300, 1060)
      ctx.drawImage('../../images/Group4.png', 490, 1030, 50, 30);

      ctx.setFontSize(28);
      ctx.setFillStyle('#000');
      ctx.fillText(that.data.albumsDescribe.slice(0, 25), 30, 1110)
      ctx.fillText(that.data.albumsDescribe.slice(25, 50), 30, 1150)
      ctx.fillText(that.data.albumsDescribe.slice(50, 75), 30, 1190)
      // 标题 2
      ctx.drawImage('../../images/Group4.png', 220, 1250, 50, 30);
      ctx.setFontSize(40);
      ctx.setFillStyle('#000');
      ctx.fillText("图案展示", 300, 1280)
      ctx.drawImage('../../images/Group4.png', 490, 1250, 50, 30);
      // 图片列表
      ctx.save();
      //开始一个新的绘制路径
      ctx.beginPath();
      //设置路径起点坐标
      ctx.moveTo(50, 1405);
      ctx.arc(125, 1405, 75, 0, Math.PI, true);
      ctx.moveTo(50, 1405);
      ctx.lineTo(50, 1555);
      ctx.lineTo(200, 1555);
      ctx.lineTo(200, 1405);
      //先关闭绘制路径。注意,此时将会使用直线连接当前端点和起始端点。
      ctx.closePath();
      ctx.stroke()
      ctx.clip();
      ctx.drawImage(url1.path, 50, 1330, 150, 225);
      ctx.restore();

      ctx.save();
      //开始一个新的绘制路径
      ctx.beginPath();
      //设置路径起点坐标
      ctx.moveTo(300, 1405);
      ctx.arc(375, 1405, 75, 0, Math.PI, true);
      ctx.moveTo(300, 1405);
      ctx.lineTo(300, 1555);
      ctx.lineTo(450, 1555);
      ctx.lineTo(450, 1405);
      ctx.closePath();
      ctx.stroke()
      ctx.clip();
      ctx.drawImage(url2.path, 300, 1330, 150, 225);
      ctx.restore();
      ctx.save();
      //开始一个新的绘制路径
      ctx.beginPath();
      //设置路径起点坐标
      ctx.moveTo(550, 1405);
      ctx.arc(625, 1405, 75, 0, Math.PI, true);
      ctx.moveTo(550, 1405);
      ctx.lineTo(550, 1555);
      ctx.lineTo(700, 1555);
      ctx.lineTo(700, 1405);
      ctx.closePath();
      ctx.stroke()
      ctx.clip();
      ctx.drawImage(url3.path, 550, 1330, 150, 225);
      ctx.restore();
      ctx.save();
      // 底部
      ctx.drawImage(qr.path, 265, 1580, qr.width * 0.8, qr.height * 0.8);
      ctx.setFontSize(28);
      ctx.setFillStyle('black');
      ctx.fillText("扫码或长按小程序识别", 225, 1830)
      ctx.fillText("查看最新美甲图案", 248, 1870);
      ctx.draw(true, function() {
        setTimeout(function() {
          that.save()
        }, 2000)
      })
    })

  },
  //生成图片
  save: function() {
    let that = this;
    wx.canvasToTempFilePath({ //canvas 生成图片 生成临时路径
      canvasId: 'canvas',
      success: function(res) {
        that.setData({
          imgSrc: res.tempFilePath
        })
      }
    })
  },
  //下载图片到本地
  downimage() {
    let that = this;
    if (that.data.imgSrc == null) {
      return;
    }
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imgSrc,
      success: (res) => {
        $Toast({
          content: '保存成功',
          type: 'success'
        });
      },
      fail: (res) => {
        if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          this.setData({
            visible: true
          })
        } else {
          this.setData({
            visible: true
          })
        }
      }
    })
  },
  //预览生成的海报图片
  preview() {
    wx.previewImage({
      urls: [this.data.imgSrc]
    })
  },
  //获取权限
  getAuth(res) {
    this.setData({
      visible: false
    })
    if (res.detail.index == 1) {
      wx.openSetting({
        success(settingdata) {}
      })
    } else {
      $Toast({
        content: '暂无权限,请授权后再试',
        type: 'warning'
      });
    }
  }

})

 

index.wxml 


  
    
      
      
    
    
      
        
        {{imgSrc==null?'海报生成中':'保存图片分享'}}
      
    
  


  暂无相册的写入权限。
 



 

index.wxss

page {
  width: 100%;
  min-height: 100%;
}

image {
  display: inline-block;
  width: 100%;
  height: 1020rpx;
}

.c1 {
  background: #fff;
}
 
.sharelunbo {
  width: 100%;
  height:100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.imgshare {
  height: 100%;
}
.phone_submit {
  width: 100%;
  text-align: center;
  margin-top: 80rpx;
}

.phone_submit .phone {
  position: relative;
  display: inline-block;
  width: 600rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 34rpx;
  color: #fff;
}

.phone_submit .phone image {
  width: 100%;
  height: 100%;
}

.phone_submit .phone text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.poster {
  width: 250px;
  height: 640px;
  margin: 0 auto;
  border-radius: 10px;
  overflow: hidden;
  margin-top: 10px;
  box-shadow: 0px 0px 15px 3px #656295;
  position: relative;
}

.poster image {
  width: 250px;
}

.hoverStyle {
  background-color: #656295;
}

 index.json

{
    "navigationBarTitleText": "海报",
  "usingComponents": {
    "i-spin": "/component/iview/spin/index",
    "i-message": "/component/iview/message/index",
    "i-modal": "/component/iview/modal/index",
    "i-toast": "/component/iview/toast/index"
  }
}

 

你可能感兴趣的:(微信小程序)