uniapp develops WeChat applets and uses painter to convert pages into pictures and save them to local photo albums

introduction

The reason why I use the painter is that when uniapp develops the WeChat applet, it needs to convert the content of a page into a picture and save it to the local photo album.
At first, I found a lot of them on the Internet uniappto html2canvas convert webpages to pictures jspdfand then convert pictures to pdf , but this method is not supported in the applet environment, and it is only h5applicable in the environment. Of course, this method is feasible, and you can use webviewthe h5The page is embedded in the WeChat applet , but my overall module has already been implemented in the WeChat applet, and time does not allow me to re-develop it h5, so I use painterthe method to convert the WeChat applet page into a picture.

1. What is a painter?

painterIt is a WeChat applet plug-in

Painter github mirror URL: https://gitcode.net/mirrors/Kujiale-Mobile/Painter?utm_source=csdn_github_accelerator#The
picture below is the official website’s own introduction to painter.
insert image description here

2. The application scenario of painter

1. Social sharing : Developers can convert users' personal information, event pages, etc. into pictures, and users can save these pictures locally and share them on Moments, Qzone and other social platforms.

2. E-commerce promotion : The e-commerce platform can convert the current product detail page into a picture, and provide it to users to share on social platforms to realize product promotion.

3. Data visualization : For some scenes that need to display a large amount of data or complex data, the data can be displayed in the form of charts, and then use painter to convert these data charts into pictures for users to download and use.

4. Save screenshots : For small programs such as quizzes, short stories, tutorials, etc., you can save the entire page with one click.

5. Generate personalized posters : For example, generate a personalized poster with the user's nickname, avatar, achievements, etc. and provide it to the user for storage to enhance user experience.

3. The custom component in uniapp references the painter

The way to refer to the custom component of the applet in uniapp
The above link is the official tutorial on how to introduce custom components in uniapp. Here I will simply record the way to introduce the custom component painter of the WeChat applet.

1. Download painter

Painter download address
insert image description here

After downloading, find the painter folder under the components folder, this is the painter component we want to use.
insert image description here
insert image description here

2. Create a new wxcomponents folder in the project root directory, and copy the downloaded painter folder to this directory

┌─wxcomponents                  微信小程序自定义组件存放目录
│   └──painter                   微信小程序自定义组件
│		├─painter.js
│		├─painter.wxml
│		├─painter.json
│		└─lib
├─pages
│  └─index
│		└─index.vue
│
├─static
├─main.js
├─App.vue
├─manifest.json
└─pages.json

insert image description here

3. Introduce components in style -> usingComponents of the page corresponding to pages.json:

insert image description here

// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
	"usingComponents": {
    
    
		"painter": "/wxcomponents/painter/painter"
	}
// #endif

4. Then you can use the painter in the page just configured

    <painter name="合同签订" :scaleRatio="2" :palette="palette" @imgOK="imgOK"
      customStyle="position:fixed;top:-9999rpx"></painter>

Fourth, the basic usage of painter

This is the introduction of the official website: The following is the picture generated by
insert image description here
a simple demo I used when I used it. The effect of the picture is as follows: the code is as follows :

insert image description here

  • template
<painter name="合同签订" :scaleRatio="2" :palette="palette" @imgOK="imgOK" style="position:fixed;top:-9999rpx"></painter>
<button @tap="saveImg">保存</button>
  • data
      imgSrc: '',

      painterStyle: {
    
    
        rect: {
    
    
          width: '710rpx',
          left: '20rpx',
          color: '#fff',
          borderRadius: '16rpx'
        },
        textLeft: {
    
    
          left: '40rpx',
          fontSize: '28rpx',
          color: '#111'
        },
        textRight: {
    
    
          right: '40rpx',
          fontSize: '28rpx',
          color: '#111'
        },
        textLeftTwo: {
    
    
          left: '180rpx',
          fontSize: '28rpx',
          color: '#111'
        },
        title: {
    
    
          textAlign: 'center',
          fontSize: '36rpx',
          color: '#000',
          width: '100%'
        },
        line: {
    
    
          left: '40rpx',
          width: '670rpx',
          height: '1px',
          color: '#eee'
        }
      }

  • computed
    // 这里是图片内容的具体实现
    palette() {
    
    
      const palette = {
    
    
        width: '750rpx',
        height: '1200rpx',
        background: '#f7f7f7',
        views: []
      }

      const startTop = 600 // 开始的 top 值
      const gapSize = 50 // 间隙大小

      // css 使用数组形式抽离相同样式
      const arr1 = [
        {
    
    
          type: 'rect', // 背景
          css: [{
    
     height: '500rpx' }, this.painterStyle.rect]
        },
        {
    
    
          type: 'rect', // 分割线
          css: [{
    
     top: '100rpx' }, this.painterStyle.line]
        },
        {
    
    
          type: 'rect', // 分割线
          css: [{
    
     top: '200rpx' }, this.painterStyle.line]
        }
      ]

      // 文字
      const arr2 = [
        {
    
    
          type: 'text',
          text: '民用天然气供用气合同',
          css: [{
    
     top: `${
      
      startTop}rpx`, }, this.painterStyle.title]
        },
        {
    
    
          type: 'text',
          text: '用户编号:',
          css: [{
    
     top: `${
      
      startTop + 2 * gapSize}rpx`,}, this.painterStyle.textLeft]
        },
        {
    
    
          type: 'text',
          text: '002',
          css: [
            {
    
    
              top: `${
      
      startTop + 2 * gapSize}rpx`,
            },
            this.painterStyle.textLeftTwo
          ]
        },
        {
    
    
          type: 'text',
          text: '合同编号:',
          css: [{
    
     top: `${
      
      startTop + 3 * gapSize}rpx`,}, this.painterStyle.textLeft]
        },
        {
    
    
          type: 'text',
          text: '123456',
          css: [
            {
    
    
              top: `${
      
      startTop + 3 * gapSize}rpx`,
            },
            this.painterStyle.textLeftTwo
          ]
        },
      ]

      palette.views = palette.views.concat(arr1, arr2)

      // 如果图片没有显示出来,可以把它放到 views 的末尾
      palette.views.push(
        {
    
    
          type: 'image',
          url: 'https://qhyxpicoss.kujiale.com/r/2017/12/04/L3D123I45VHNYULVSAEYCV3P3X6888_3200x2400.jpg@!70q',
          css: {
    
    
            top: '48rpx',
            right: '48rpx',
            width: '192rpx',
            height: '192rpx',
          },
        }
      )

      return palette
    },
  • methods
    // 图片生成成功,可以从 e.detail.path 获取生成的图片路径
   imgOK(e) {
    
    
     console.log('e', e)
     this.imgSrc = e.detail.path
     console.log('imgSrc', this.imgSrc) // 点击打印出来的内容就可以看见图片了
   },

   // 保存图片
   saveImg() {
    
    
     //用户授权并开启保存到相册的权限
     uni.authorize({
    
    
       scope: 'scope.writePhotosAlbum',
       success: (result) => {
    
    
         if (!this.imgSrc) {
    
    
           return uni.showToast({
    
    
             title: '图片生成中,请稍等~',
             icon: 'none'
           })
         }
         // 保存到手机相册
         uni.saveImageToPhotosAlbum({
    
    
           filePath: this.imgSrc,
           success: function (e) {
    
    
             console.log('保存成功', e)
             uni.showToast({
    
    
               title: '保存成功',
               icon: 'none'
             })
           }
         })
       },
       fail: (error) => {
    
    
         uni.showModal({
    
    
           title: '提示',
           content: '检测到您有未开启的权限,为保证功能正常使用,请保持保存到相册权限均为开启状态',
           confirmText: '去开启',
           success: ({
     
      confirm }) => {
    
    
             if (confirm) uni.openSetting()
           }
         })
       }
     })
   },

This is just the most basic usage, for more requirements, please refer to the official website.

Summarize

Well, the above is how to UniAppuse the plug-in in the development environment Painterto convert the WeChat applet page into a picture and save it to the local photo album. First, we describe the detailed steps of installation and configuration , including how to import and write drawing data Painterin the project . Then, we focused on how to draw the required pictures on the web, including text, pictures, rectangles and other elements, and explained in detail how to control the drawing position, size and style of these elements. Finally, we introduced how to save the drawn picture to the user's local photo album through the WeChat applet. I hope to see the friends here, this record will be helpful to youPainterPainterJSONPainterCanvasAPICanvas

Guess you like

Origin blog.csdn.net/jieyucx/article/details/132311144