欢迎您访问南京安优网络官方网站,本公司专注于:网站制作、小程序开发、网站推广。 24小时服务热线:400-8793-956
当前位置:南京网站制作公司 > 资讯中心 > 网站知识
南京小程序开发解析小程序的生成图像保存到相册
来源:南京网站制作 时间:2019-10-28 08:18:21

需求总结:

在电子商务项目中,我们需要将自己的小商店的产品与我们的小程序代码一起生成海报,将其保存在本地,然后在无所不能的朋友圈,QQ空间,微博等中共享它们。 。为它们做广告…下面跟着南京小程序开发安优网络来一起看看:
 
如下图所示,依次显示了三种海报格式。左右滑动以切换到海报,单击下面的保存图片以将当前海报保存到移动相册。
将微信小程序的生成图像保存到相册

思维
需要产品信息,用户信息和小程序代码。
使用刷卡器组件显示海报。
通过wx.createcanvascontext 将海报绘制到canvas画布组件上。
通过使用canvas到tempfilepath将canvas海报保存到本地临时文件路径;
使用saveimagetophotosalbum将图片保存到本地相册
根据滑动组件的当前属性判断当前保存的海报
根据想法逐步实现:
 
产品信息,用户信息和小程序代码
1.产品信息通过导航事件转移到张贴者页面,我在其中使用模拟数据;
2.用户信息通过wx.setstoragesync存储到缓存中。
 
// index.js
   //Event handler
  navToShare: function () {
    //Analog data
    var data = {
      thumb_images: [
        'https://cbu01.alicdn.com/img/ibank/2018/544/692/8567296445_882293189.400x400.jpg',
        'https://cbu01.alicdn.com/img/ibank/2018/971/643/8581346179_882293189.400x400.jpg',
        'https://cbu01.alicdn.com/img/ibank/2018/184/392/8567293481_882293189.400x400.jpg'
      ],
      Name: 'wholesale trend of new hollow round neck bat short sleeve T-shirt for women's Korean loose cotton blouse in summer 2018',
      price: 198,
    }
     wx.navigateTo({
        url: '../poster/poster?data=' + encodeURIComponent(JSON.stringify(data))
      })
  },
3.在发布者页面的onload函数的参数中获取产品信息
。4.在发布者页面的本地缓存中获取用户信息wx.getstoragesync。5
.由于画布绘图图片不支持跨域图片,因此请首先使用getimageinfo返回网络图片到图片的本地路径。
 
// poster.js
  onLoad: function(options) {
    var data = JSON.parse(decodeURIComponent(options.data));
    var userinfo;
    //Get the user's Avatar and nickname stored locally 
      userinfo = wx.getStorageSync('userInfo');
    Console.log ('user information ', userinfo)
    //Render page
    this.setData({
      avatar_url: userinfo.avatarUrl,
      nickname: userinfo.nickName,
      thumb_images: data.thumb_images,
      pro_price: data.price,
      pro_name: data.name,
    })
 
    //Save network picture to local for canvas drawing picture
    wx.getImageInfo({
      src: userinfo.avatarUrl,
      success: (res) => {
        tmpAvatarUrl = res.path;
      }
    });
    //Save product map to local for canvas drawing
    var thumbs = data.thumb_images;
    Tmpthumbs = []; // clear first, and then add a new product map
    thumbs.forEach((item, i) => {
      wx.getImageInfo({
        src: item,
        success: (res) => {
          tmpThumbs.push(res.path)
        }
      })
    });
  },
7. applet代码是由后端生成的。前端通过发布请求传递数据,返回小程序代码URL,并使用wx.getimageinfo将其保存在本地。
 
//Post method after encapsulation
     wxRequest.postRequest(url, data).then(res => {
                  if (res.data.error_code == 0) {
                  //Save the applet code locally for canvas drawing
                    wx.getImageInfo({
                      src: res.data.qrcode,
                      success: (result) => {
                        this.setData({
                          poster_qrcode: result.path
                        })
                      }
                    });
                  }
                })
展示带有滑动组件的海报
在此项目中,我将页面渲染与画布渲染分开,因为小程序单元rpx自动适应各种设备屏幕。画布绘制单位为px。我没有在PX和rpx之间进行计算。保存PX单元的固定尺寸图片也很好。
 
<view class='poster_swiper'>
      <swiper bindchange="shareChange" current="{{current}}" circular="{{circular}}" previous-margin="100rpx" next-margin="100rpx" class="swiper_share">
        <swiper-item class="swiper_item1">
          //Render pages according to design
        </swiper-item>
        <swiper-item class="swiper_item2" wx:if="{{thumb_images.length>1}}">
          //Render pages according to design
        </swiper-item>
        <swiper-item class="swiper_item3" wx:if="{{thumb_images.length>2}}">
           //Render pages according to design
        </swiper-item>
      </swiper>
    </view>
在这里,我们使用swiper的几个属性来列出它们。
 
当前 0 当前滑块的索引
布尔型 是否采用联合滑动
前利润 “ 0px” 前页边距可用于暴露前一项的一小部分,接受PX和rpx值 1.9.0
下一个保证金 “ 0px” 可以用于暴露后一项的一小部分的后边距接受PX和rpx值 1.9.0
绑定更改 事件句柄 当前事件更改时将触发更改事件。详细信息= {当前:当前,来源:来源}
通过wx.createcanvascontext将海报绘制到画布组件。
1.在wxml中添加画布组件,并设置画布ID,以便wx.createcanvascontext可以绘制画布。
 
<canvas class='canvas-poster' canvas-id='canvasposter'></canvas>
定义样式是固定的,并且位于可见区域之外,而不会影响可见区域的显示。
 
.canvas-poster {
  position: fixed;
  width: 280px;
  height: 450px;
  top: 100%;
  left: 100%;
  overflow: hidden; 
}
分别绘制了三种海报。有关详细信息,请参见注释。
 
/*A product map*/
  drawPosterOne: function() {
    var ctx = wx.createCanvasContext('canvasposter');
    // ctx.clearRect(0, 0, 280, 450);
    /*Draw background*/
    ctx.rect(0, 0, 280, 450);
    ctx.setFillStyle('white');
    ctx.fillRect(0, 0, 280, 450);
    /*Draw store name*/
    ctx.setFontSize(16);
    ctx.setFillStyle('#333');
    ctx.textAlign = "center";
    CTX. Filltext (this. Data. Nickname + 'shop', 140, 70);
    ctx.restore();
    /*Drawing product drawings*/
    ctx.drawImage(tmpThumbs[0], 35, 90, 210, 210);
    /*Draw product name background*/
    ctx.setFillStyle('#FF8409');
    ctx.fillRect(35, 300, 210, 60);
    /*Draw product name*/
    ctx.setFontSize(12);
    ctx.setFillStyle('#ffffff');
    ctx.textAlign = "left";
    ctx.fillText(this.data.pro_name.substr(0, 18), 45, 322);
    ctx.restore();
    ctx.setFontSize(12);
    ctx.setFillStyle('#ffffff');
    ctx.textAlign = "left";
    ctx.fillText(this.data.pro_name.substr(18, 20), 45, 344);
    ctx.restore();
    /*Draw wireframe*/
    ctx.setLineDash([1, 3], 1);
    ctx.beginPath();
    ctx.moveTo(35, 375);
    ctx.lineTo(160, 375);
    ctx.moveTo(35, 435);
    ctx.lineTo(160, 435);
    ctx.setStrokeStyle('#979797');
    ctx.stroke();
    ctx.restore();
    /*Draw text*/
    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.textAlign = "left";
    ctx.fillText('¥', 35, 400);
    ctx.setFontSize(18);
    ctx.fillText(this.data.pro_price, 50, 400);
    ctx.setFontSize(11);
    ctx.setFillStyle('#666666');
    ctx.fillText(this.data.poster_qrtext, 35, 420);
    ctx.restore();
    /*Draw QR code*/
    ctx.drawImage(this.data.poster_qrcode, 185, 370, 60, 60);
    ctx.restore();
    /*Round head*/
    ctx.save()
    ctx.beginPath();
    ctx.arc(140, 30, 20, 0, 2 * Math.PI)
    ctx.setFillStyle('#fff')
    ctx.fill()
    ctx.clip()
    ctx.drawImage(tmpAvatarUrl, 120, 10, 40, 40)
    ctx.restore()
    ctx.draw(false, this.getTempFilePath);
  },
  /*Two product drawings*/
  drawPosterTwo: function() {
    var ctx = wx.createCanvasContext('canvasposter');
    /*Draw background*/
    ctx.rect(0, 0, 280, 450);
    ctx.setFillStyle('white');
    ctx.fillRect(0, 0, 280, 450);
    /*Draw store name*/
    ctx.setFontSize(14);
    ctx.setFillStyle('#333');
    ctx.textAlign = "left";
    CTX. Filltext (this. Data. Nickname + 'shop', 65, 36);
    ctx.restore();
    /*Draw dashed box*/
    ctx.setLineDash([4, 1], 1);
    ctx.beginPath();
    ctx.moveTo(25, 60);
    ctx.lineTo(255, 60);
    ctx.moveTo(25, 325);
    ctx.lineTo(255, 325);
    ctx.setStrokeStyle('#979797');
    ctx.stroke();
    ctx.restore();
    /*Draw product name*/
    ctx.setFontSize(12);
    ctx.setFillStyle('#333');
    ctx.textAlign = "left";
    ctx.fillText(this.data.pro_name.substr(0, 13), 25, 82);
    ctx.setFontSize(12);
    ctx.setFillStyle('#333');
    ctx.fillText(this.data.pro_name.substr(13, 12) + '...', 25, 100);
    ctx.restore();
    /*Draw text*/
    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.textAlign = "left";
    ctx.fillText('¥', 190, 90);
    ctx.setFontSize(16);
    ctx.fillText(this.data.pro_price, 205, 90);
    ctx.restore();
    ctx.setFontSize(10);
    ctx.setFillStyle('#666666');
    ctx.textAlign = "center";
    ctx.fillText(this.data.poster_qrtext, 140, 420);
    ctx.restore();
    /*Drawing product drawings*/
    ctx.drawImage(tmpThumbs[0], 25, 115, 110, 150);
    ctx.drawImage(tmpThumbs[1], 145, 115, 110, 150);
    ctx.restore();
    /*Draw text*/
    ctx.setFontSize(12);
    ctx.setFillStyle('#333333');
    ctx.textAlign = "left";
    ctx.fillText(this.data.slogan1, 25, 290);
    ctx.fillText(this.data.slogan2, 25, 308);
    ctx.restore();
    /*Draw QR code*/
    ctx.drawImage(this.data.poster_qrcode, 110, 330, 70, 70);
    ctx.restore();
    /*Round head*/
    ctx.save()
    ctx.beginPath();
    ctx.arc(35, 30, 20, 0, 2 * Math.PI)
    ctx.setFillStyle('#fff')
    ctx.fill()
    ctx.clip()
    ctx.drawImage(tmpAvatarUrl, 15, 10, 40, 40)
    ctx.restore()
    ctx.draw(false, this.getTempFilePath);
  },
  /*Three product drawings*/
  drawPosterThree: function() {
    var ctx = wx.createCanvasContext('canvasposter');
    /*Draw background*/
    ctx.rect(0, 0, 280, 450);
    ctx.setFillStyle('white');
    ctx.fillRect(0, 0, 280, 450);
    /*Draw store name*/
    ctx.setFontSize(16);
    ctx.setFillStyle('#333');
    ctx.textAlign = "center";
    CTX. Filltext (this. Data. Nickname + 'shop', 140, 70);
    ctx.restore();
    /*Draw dashed box*/
    ctx.beginPath()
    ctx.setLineDash([4, 1], 1);
    ctx.beginPath();
    ctx.moveTo(20, 230);
    ctx.lineTo(145, 230);
    ctx.lineTo(145, 305);
    ctx.lineTo(40, 305);
    /*Lower left corner fillet CTX. Arcto (, lower left corner left coordinate, upper left corner left coordinate, radius)*/
    ctx.arcTo(20, 305, 20, 230, 20);
    ctx.moveTo(20, 230);
    ctx.lineTo(20, 285);
    ctx.setStrokeStyle('#333333')
    ctx.stroke()
    ctx.setStrokeStyle('#979797');
    ctx.stroke();
    ctx.restore();
    /*Draw product name*/
    ctx.setFontSize(12);
    ctx.setFillStyle('#333');
    ctx.textAlign = "left";
    ctx.fillText(this.data.pro_name.substr(0, 9), 30, 250);
    ctx.setFontSize(12);
    ctx.setFillStyle('#333');
    ctx.fillText(this.data.pro_name.substr(9, 8) + '...', 30, 268);
    ctx.restore();
    /*Draw text*/
    ctx.setFontSize(14);
    ctx.setFillStyle('#333333');
    ctx.textAlign = "left";
    ctx.fillText('¥', 30, 290);
    ctx.setFontSize(16);
    ctx.fillText(this.data.pro_price, 45, 290);
    ctx.restore();
    ctx.setFontSize(10);
    ctx.setFillStyle('#666666');
    ctx.textAlign = "center";
    ctx.fillText(this.data.poster_qrtext, 140, 420);
    ctx.restore();
    /*Drawing product drawings*/
    ctx.drawImage(tmpThumbs[0], 20, 90, 125, 125);
    ctx.drawImage(tmpThumbs[1], 160, 90, 100, 100);
    ctx.drawImage(tmpThumbs[2], 160, 205, 100, 100);
    ctx.restore();
    ctx.restore();
    /*Draw QR code*/
    ctx.drawImage(this.data.poster_qrcode, 110, 330, 70, 70);
    ctx.restore();
    /*Round head*/
    ctx.save()
    ctx.beginPath();
    ctx.arc(140, 30, 20, 0, 2 * Math.PI)
    ctx.setFillStyle('#fff')
    ctx.fill()
    ctx.clip()
    ctx.drawImage(tmpAvatarUrl, 120, 10, 40, 40)
    ctx.restore()
    ctx.draw(false, this.getTempFilePath);
  },
图中使用的数据如下
 
Var tmpavatarurl = ""; / * used to draw the head image*/
Var tmpthumbs = []; / * for product mapping*/
Var drawing = false; / * avoid clicking the Save button multiple times*/
Page({
  /**
   *Initial data of the page
   */
  data: {
    Circular: true, // whether or not the swiper adopts cohesion sliding
    Current: 0, // index of the slider where the swiper is currently located
    Avatar_url: '', // render the Avatar
    Nickname: '', // render nickname
    Postcode: '/ images / postcode. PNG', // applet code
    Post qurtext: 'long press identification to view goods',
    Pro_name: '', // product name
    Pro_price: '', // product price
    Slogan1: 'my store is new', // slogan 1
    Slogan2: 'come on, let's have a look together!', // slogan 2
    Thumb image: [] // render image
  },
通过使用canvas到tempfilepath将canvas海报保存到本地临时文件路径;
//Get temporary path
  getTempFilePath: function() {
    wx.canvasToTempFilePath({
      canvasId: 'canvasposter',
      success: (res) => {
        this.saveImageToPhotosAlbum(res.tempFilePath)
      }
    })
  },
使用saveimagetophotosalbum将图片保存到本地相册
//Save to album
  saveImageToPhotosAlbum: function(imgUrl) {
    if (imgUrl) {
      wx.saveImageToPhotosAlbum({
        filePath: imgUrl,
        success: (res) => {
          wx.showToast({
            Title: 'saved successfully',
            icon: 'success',
            duration: 2000
          })
          drawing = false
        },
        fail: (err) => {
          wx.showToast({
            Title: 'save failed',
            icon: 'none',
            duration: 2000
          })
          drawing = false
        }
      })
    }else{
      wx.showToast({
        Title: 'drawing... ',
        icon: 'loading',
        duration: 3000
      })
    }
  },
Note that canvas painting takes time, so set drawing to prevent painting from being interrupted
 
根据滑动组件的当前属性判断当前保存的海报
1.首先根据变化事件设置电流
 
 shareChange: function(e) {
    if (e.detail.source == 'touch') {
      this.setData({
        current: e.detail.current
      })
    }
  },
2.单击按钮将海报保存到手机相册。
 
<view class="common_btn" catchtap="savePoster">
    < text > Save Picture < / text >
  </view>
Judge whether to obtain album authorization. If you have obtained permission, draw directly. If you have not obtained permission, you need to prompt the user to set authorization.
 
/*Save poster to mobile album*/
  savePoster: function(e) {
    var that = this;
    var current = this.data.current;
    //Get album authorization
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            Success() {// here is the callback after the user agrees to authorize.
              that.drawPoster(current);
            },
            Fail() {// here is the callback after the user rejects the authorization.
              wx.showModal({
                Title: 'prompt',
                Content: 'if you do not open the authorization, you cannot save the picture in the album! ',
                showCancel: true,
                Canceltext: 'to authorize',
                cancelColor: '#000000',
                Confirmtext: 'do not authorize temporarily',
                confirmColor: '#3CC51F',
                success: function(res) {
                  if (res) {
                    wx.openSetting({
                      //Call the client applet setting interface to return the operation result set by the user.
                    })
                  } else {
                    //Console. Log ('user clicks Cancel ')
                  }
                }
              })
            }
          })
        }Else {// the user has been authorized. 
          that.drawPoster(current);
        }
      }
    })
  },
3.判断当前海报,并根据当前海报绘制相应的海报
 
/*Draw posters*/
  drawPoster: function(current) {
    if(drawing){
      wx.showToast({
        Title: 'drawing... ',
        icon: 'loading',
        duration: 3000
      }) 
    }else{
      drawing = true;
      // loading 
      //Draw the corresponding poster according to the index of the current slider of swiper
      switch (current) {
        case 0:
          this.drawPosterOne()
          break;
        case 1:
          this.drawPosterTwo()
          break;
        case 2:
          this.drawPosterThree()
          break;
      }
    }
   
  },

以上就是今天南京小程序开发安优网络带来的全部内容,希望以上的内容能够帮助到你们,谢谢!


本文地址:http://www.njanyou.cn/web/2819.html
Tag:
专业服务:南京网站制作,南京网站制作公司,南京网站建设公司
联系电话:025-65016872
上一篇: 南京网站制作公司认为明智企业家的网站设计技巧
下一篇: 南京网站制作公司从今天开始,从您的网站开始产生潜在客户的20条技巧
最新案例
永银
永银
珠海跨境电商
珠海跨境电商
五颗星商城
五颗星商城
上海万客生鲜超市
上海万客生鲜超市
一九在线商城
一九在线商城
你可能感兴趣
使用选择轮使网站导航变得有趣的便捷指南
在您的网站上使用不寻常和醒目的颜色的 6 种方法
花店的基本数字营销策略
SEO的内部链接最佳实践
捕捉自信:摄影在男士时尚品牌中的作用
2024年房地产网站的创新网页设计趋势
南京网站制作说说哪些关键因素使商业网站成功?
南京网站制作公司分享使用 iPhone 拍摄更好网站照片的 7 个技巧
最后更新
南京网页制作开发在 SEO 中的作用 南京网站设计的几个技巧帮助你的论文更有趣和吸引人 南京网站建设是如何在 Photoshop 中创建网站横幅 南京网站制作公司如何为您的企业选择最佳的电子邮件营销软件 南京网站制作:您需要聘请网站设计公司的 10 个理由 南京网站设计:2024 个流行的网站设计趋势 如果需要改造在线商店南京网站建设认为需要考虑的 8 件事 南京网站制作公司分享使用 iPhone 拍摄更好网站照片的 7 个技巧
服务项目
南京网站制作 营销型网站 微信营销 IDC网站 精品案例